Include current class as return type annotation

In python 3, I can create 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 that I cannot make an annotation with the return type of the current class (Graph), which is not yet defined. Example:

 class Graph: def reverse(self) -> Graph: pass 

This code comes with an error

 def reverse(self) -> Graph: NameError: name 'Graph' is not defined 

These annotations are really useful for both documentation and the IDE for recognizing arguments and return types => enable autocomplete

UPD: So I came, it’s either impossible, or it requires some hacks that I don’t like, so I decided to use only def reverse (self) -> 'Graph': which is clear for documentation, but breaks the rule. The disadvantage is that it does not work for IDE autocomplete.

+84
python class annotations
Apr 6 '13 at
source share
2 answers

So, after a while, I can say that the decision I made was to use -> 'Graph' instead of -> Graph . This does not make my IDE (PyCharm) able to recognize a type this way, but it works well enough for documentation purposes.

Another possible solution that I could use was to change the annotation at runtime, but this does not solve the documentation problem - you will not want to look for type declarations somewhere in the middle of the sources ...

The problem is rooted in recognizing a class object before the class has been defined. This is simply not possible to do in python.

+53
Jul 08 '13 at 21:04 on
source share

In python-3.7, this problem was solved by not evaluating annotations during function definition. Instead, they are stored in __annotations__ as a string. This is called the pending annotation score presented in PEP 563 .

Also note:

Depreciation policy

Starting with Python 3.7, __future__ imports are required to use the described functionality. There are no warnings.

In Python 3.8, PendingDeprecationWarning calls PendingDeprecationWarning when there are type annotations in modules without importing __future__ .

Starting in Python 3.9, a warning becomes a warning about DeprecationWarning .

In Python 4.0, this will become the default behavior. Using annotations incompatible with this PEP is no longer supported.

Here is an example:

 In [7]: from __future__ import annotations In [8]: class C: ...: def func(cls, arg:str) -> C: ...: pass ...: In [9]: c = C() 
+27
Apr 17 '18 at 7:36
source share



All Articles