I'm trying to create a method that takes self and another instance of the same method as its arguments, for example:
class AClass():
def __init__(self, v:int)->None:
self.var = v
def a_method(self, other: AClass)->None:
self.var = other.var
using the type hint other: AClass
isn't recognised, and as such, the .var of other.var
isn't highlighted in my IDE. My plan currently is to just remove the type hint, is there a more correct way to do this?
CodePudding user response:
Because this is to use itself as an annotation inside the class, it can't be completely parsed. The correct way is to use the string:
def a_method(self, other: 'AClass') -> None:
...
CodePudding user response:
That is not working because AClass
is not yet fully evaluated when you use it as type hint in one of its method. So at that time the AClass
identifier is not yet available.
That is discussed at length in PEP563: https://peps.python.org/pep-0563/
So you have 2 solutions:
as already mentioned by @Mechanic Pig: turn the annotation into a string:
def a_method(self, other: 'AClass') -> None:
Note that tools that use type hint (such as
mypy
or doc generators) will 'convert back' that string into the appropriate type when they run.or enable Postponed Evaluation of Annotations by adding this line at the beginning of the file:
from __future__ import annotations class AClass: def a_method(self, other: AClass) -> None: ...
As the name suggests, when you enable Postponed Annotation Evaluation, the type annotations are ignored at first, then evaluated only after the whole file has been evaluated, so the
AClass
identifier is available at that time.