Jon Jon - 1 month ago 12
Python Question

Type-Hints: How can I indicate that I want to return an instance of the actual class?

When I try to combine Type Hints and object creation through
a

classmethod
I get the following
NameError
:

NameError: name 'Person' is not defined


How can I indicate through type hinting that I want to return an
instance of the class which I am currently defining? (see example)





Example:

The definition of the
classmethod
from_dict
fails because Python cannot resolve the
class Person
.

class Person:

def __init__(self, name: str):
self.name = name

@classmethod
def from_dict(self, info: dict) -> Person:
person_obj = Person(info['name'])
return person_obj

def speak(self, word: str) -> str:
print(word)
return self.name + 'said' + word

Answer

You need to use a TypeVar.

from typing import TypeVar
PersonType = TypeVar("PersonType", bound="Person")

class Person:
    @classmethod
    def from_dict(self, info: dict) -> PersonType:
        person_obj = Person(info['name'])
        return person_obj
Comments