Search code examples
pythontyping

Why is TypeError raised when attribute name matches class name using typing?


I'm unable to initialise a dataclass list attribute where the attribute has the same name as the list elements' class.

The initialisation works fine when the attribute name is changed. I have the same problem with Pydantic classes.

from dataclasses import dataclass, field
from typing import List

@dataclass
class Thing:
    name: str

@dataclass
class MyClass:
    Thing: List[Thing] = field(default_factory=list)

c = MyClass()

This gives the following error:

TypeError: Parameters to generic types must be types. Got Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object at 0x00000201CA208518>,default_f.

When I change:

    Thing: List[Thing] = field(default_factory=list)

to:

    thing: List[Thing] = field(default_factory=list)

the TypeError is not raised.


Solution

  • Because then it's overriding Thing.

    That's why thing works.