How do I comment out a Python3 method that returns self?

Feature Annotations: PEP-3107

Background: I'm a PyCharm user with CPython 3.4x on Linux. I find it helps to annotate function parameters and return types. The IDE can hint better when I use these methods.

Question. For self-linking methods, how can I annotate the return value of the method? If I use a 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

right before the class declaration, it works. However, I don't know if there are unintended negative side effects from this technique.

+3


source to share


1 answer


You can 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 was not defined until after the class definition is complete.



Same problem: including the current class in the return type annotation

His solution was to use a string. In your code that will be -> 'X'

0


source







All Articles