How to annotate a Python3 method that returns self?
Asked Answered
H

3

9

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.

Hygienic answered 16/11, 2014 at 5:37 Comment(0)
G
7

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
Gigue answered 5/8, 2022 at 15:24 Comment(1)
Very nice update! This is now the correct answer.Hygienic
E
1

While return Self might be the most ideal solution, you could also do a stringified return type of class X

class X:
    def yaya(self, x: int):
        # Do stuff here
        pass

    def chained_yaya(self, x: int) -> "X":
        # Do stuff here
        return self
Ebonyeboracum answered 23/7 at 10:27 Comment(0)
S
0

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'

Socratic answered 16/11, 2014 at 5:55 Comment(2)
String solution became the official one (as a result e.g. PyCharm fully supports it) - look here: python.org/dev/peps/pep-0484/#forward-references.Chartreuse
In modern days you can use from __future__ import annotations at the top of the file to allow foward references for annotations (see details in the link above).Higgs

© 2022 - 2024 — McMap. All rights reserved.