Asked By – sasha.sochka
In python 3 I can make arguments and return type annotations. Example:
class Graph: def __init__(self, V: int, E: int, edges: list): pass @classmethod def fromfile(cls, readobj: type(sys.stdin)): pass def V(self) -> int: pass def E(self) -> int: pass
The problem is I can’t make an annotation with return type of the current class (Graph), which is not defined yet.
class Graph: def reverse(self) -> Graph: pass
This code goes with error
def reverse(self) -> Graph: NameError: name 'Graph' is not defined
These annotations are really useful both for documenting and allowing IDE to recognize argument and return types => enable autocomplete
So what I came up is this is either impossible or requires some hacks I don’t like, so I decided to use just
def reverse (self) -> 'Graph':
which is understandable for documentation although breaks the rule. The downside is that it doesn’t work for IDE autocomplete.
Now we will see solution for issue: putting current class as return type annotation [duplicate]
So now after a while I can say that decision I took was using
-> 'Graph' instead of
-> Graph. It does not make my IDE (PyCharm) able to recognize a type this way but it just works well enough for documentation purposes.
Another possible solution I could use was changing annotation at runtime but that doesn’t solve the problem with documentation – you won’t want to look for type declarations somewhere in the middle of sources…
The problem has roots in recognizing class object before the class was actually defined. That is simply impossible to do in python.