Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotating the return type of a staticmethod in Python3 [duplicate]

Tags:

python-3.x

I'm starting to use more of Python3's typing support and I'd like to be able to annotate the return type of staticmethods that are acting as alternative constructors.

A minimal example follows; if I include the annotation it fails with:

def from_other_datastructure(json_data: str) -> MyThing:
    NameError: name 'MyThing' is not defined
import typing


class MyThing:
    def __init__(self, items: typing.List[int]):
        self.items = items

    @staticmethod
    def from_other_datastructure(json_data: str):
        return MyThing(
            [int(d) for d in json_data.split(',')]
        )

if __name__ == '__main__':
    s1 = MyThing([1, 2, 3])

    s2 = MyThing.from_other_datastructure("2,3,4")

So how does one reference a class before it has been defined for type annotations?

like image 545
Hardbyte Avatar asked Dec 11 '25 14:12

Hardbyte


1 Answers

Right after posting I found the right answer - Forward References can be defined as strings.

So the correct answer is rather simple, and as a bonus is picked up by PyCharm:

@staticmethod
def from_other_datastructure(json_data: str) -> 'MyThing':
    return MyThing(
        [int(d) for d in json_data.split(',')]
    )

https://www.python.org/dev/peps/pep-0484/#forward-references

like image 174
Hardbyte Avatar answered Dec 14 '25 13:12

Hardbyte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!