get_type_hints raise NamError with local class

304 Views Asked by At

I am using the python function typing.get_type_hints(). Unfortunately this function raise an error when I pass a local class that contains a reference to itself.

Is this a bug or am I doing something wrong ?
If indeed it's a bug where should I report it ?

from typing import *

class Tata:
    parent: "Tata"

def example():
    class Toto:
        parent: "Toto"

    print(get_type_hints(Tata))
    print(get_type_hints(Toto))  # Raise NameError: name 'Toto' is not defined

1

There are 1 best solutions below

0
Harshith Thota On

Use the class itself as the Type Hint, instead of strings (they end up becoming Forward References and it will lead to namespace conflicts)

from typing import get_type_hints

class Tata:
    parent: str = "Tata"

def example():
    class Toto:
        parent: Tata

    print(get_type_hints(Tata))
    print(get_type_hints(Toto))

example()