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?
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
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