0

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?

2
  • Which IDE are you using? Commented Apr 29, 2022 at 9:38
  • Your code may work as posted in python3.10. Which version are you using? Commented Apr 29, 2022 at 9:51

2 Answers 2

2

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:
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing, this worked as expected. Thank you!
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.