I recently found out about typehints and have been trying to include them in my code. However, I am getting TypeErrors when I use them within functions 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 typehint 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 typehint.
I am on Python version 3.11.5 for reference.
tl;dr: I tried to use a typehint of user defined classes with the union ‘|’ symbol and a TypeError was thrown.
bemy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.