I am trying to include type hints in my code. However, I am getting TypeError
s when I use them within methods in a class.
Here is a snippet of code representing the issue I am facing:
class MyClass1:
def __init__(self, ID: str) -> None:
# Some code
pass
# More code follows
class MyClass2:
def __init__(self, variables: 'MyClass1' | list['MyClass1']) -> None:
self.variables: list['MyClass1'] = to_list(variables)
# More code follows
I am having an error thrown:
TypeError: unsupported operand type(s) for |: 'str' and 'types.GenericAlias'
for the line:
def __init__(self, variables: 'MyClass1' | list['MyClass1']) -> None:
Is this the incorrect way to type hint user defined classes? Not sure what I am doing wrong here but clearly Python thinks that I am trying to compare a string and a list rather than just writing a type hint.
I am on Python version 3.11.5.
bemy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
You don’t need to wrap the type hints in a string if it’s already defined:
class MyClass2:
def __init__(self, variables: MyClass1 | list[MyClass1]) -> None:
self.variables: list[MyClass1] = to_list(variables)
In case there is a circular reference or something like that that means you can’t just do it like that, you can also wrap the entire thing in quotes:
class MyClass2:
def __init__(self, variables: 'MyClass1 | list[MyClass1]') -> None:
self.variables: list[MyClass1] = to_list(variables)
Note that variable annotations, unlike function annotations or class annotations don’t need to be wrapped in strings, because they never get evaluated and can’t be accessed at runtime anyway.