Jon Jon - 1 year ago 71
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

I get the following

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)


The definition of the
fails because Python cannot resolve the
class Person

class Person:

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

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

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

Answer Source

You need to use a TypeVar.

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

class Person:
    def from_dict(self, info: dict) -> PersonType:
        person_obj = Person(info['name'])
        return person_obj
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download