Skip to content

Add proper type annotations for containers / fields #2993

@maxnoe

Description

@maxnoe

Please describe the use case that requires this feature.

Currently, type checkers complain about the containers / fields a lot.

Investigating a bit, it should be possible to make type checkers happy by properly adding annotations and overloads to Container and Field, which should also much improve the development process in IDEs.

Describe the solution you'd like

Minimal, gemini-assisted example for a Container / Field implementation that is properly type annotated:

from typing import Any, Generic, TypeVar, Union, overload, Type
from typing_extensions import Self # Use 'from typing' in Python 3.11+

T = TypeVar("T")

class Field(Generic[T]):
    def __init__(self, default_factory: Type[T]) -> None:
        self.default_factory = default_factory
        self._name = ""

    def __set_name__(self, owner, name):
        self._name = name

    # 1. When accessed via an instance (e.g., c.foo)
    @overload
    def __get__(self, instance: Any, owner: Any) -> T: ...

    # 2. When accessed via the class (e.g., MyContainer.foo)
    @overload
    def __get__(self, instance: None, owner: Any) -> Self: ...

    def __get__(self, instance: Any, owner: Any) -> Union[T, Self]:
        if instance is None:
            return self
        return instance.__dict__[self._name]

    def __set__(self, instance: Any, value: T) -> None:
        instance.__dict__[self._name] = value

class SomeClass:
    pass


class Container:
    def __init__(self):
        for k, v in self.__class__.__dict__.items():
            if isinstance(v, Field):
                self.__dict__[k] = v.default_factory()

class MyContainer(Container):
    # Pyright infers Field[SomeClass]
    foo = Field[SomeClass | None](default_factory=SomeClass)

c = MyContainer()
# Type checker now sees 'reveal_type(c.foo)' as 'SomeClass'
val = c.foo

# no complain
c.foo = None
# no complain
c.foo = SomeClass()
# complains
c.foo = 1.0
print(c.foo)

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions