Function Annotations: PEP-3107
Background: I am PyCharm user w/CPython 3.4x on Linux. I find it helps to annotate function parameters and return types. The IDE can better hint when I use these methods.
Question: For self-chaining methods, how can I annotate the method return value? If I use the class name, Python throws an exception at compile time: NameError: name 'X' is not defined
Sample code:
class X:
def yaya(self, x: int):
# Do stuff here
pass
def chained_yaya(self, x: int) -> X:
# Do stuff here
return self
As a trick, if I put X = None
just before the class declaration, it works. However, I don't know if there are unforseen, negative side effects from this technique.
As of Python 3.11, you will be able to use Self
to annotate the return type:
from typing import Self
class X:
def yaya(self, x: int):
# Do stuff here
pass
def chained_yaya(self, x: int) -> Self:
# Do stuff here
return self
PEP 673
You could do:
class X:
pass
class X:
def yaya(self, x: int):
# Do stuff here
pass
def chained_yaya(self, x: int) -> X:
# Do stuff here
return self
In your code, X has not been defined until the class definition is complete.
Same problem here: putting current class as return type annotation
His solution was to use a string. In your code that would be -> 'X'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With