[Python] Type-hinting a dynamic, asymmetric class property

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    I'm currently working on removing all the type errors from my Python project in VS Code.

    Assume you have a Python class that has an asymmetric property. It takes any kind of iterable and converts it into a custom list subclass with additional methods.

    class ObservableList(list):
    """list with events for change, insert, remove, ..."""
    # ...

    class MyFrame:
    @property
    def my_list(self) -> ObservableList:
    return self._my_list
    @my_list.setter
    def my_list(self, val: typing.Iterable):
    self._my_list = ObservableList(val)
    # ...

    my_frame = MyFrame()


    VS Code (i.e. Pyright) will correctly deduce that:

    • you can set my_frame.my_list using any iterable, and
    • my_frame.my_list will always be an ObservableList.

    Now, let's assume that there is no actual @property code. Instead, the property is implemented dynamically using __setattr__ and __getattr__. (Context: We're talking about a GUI generator which provides automatic bindings.)

    I want to use a declaration on class level to tell the typechecker that this property exists, without actually spelling it out:

    class MyFrame(AutoFrame):
    my_list: ???
    # ...


    (AutoFrame provides the __getattr__/ __setattr__ implementation.) What can I put in place of the ??? to make this work?

    • When using ObservableList, Pyright complains when I assign a plain list to the property.
    • When using Iterable or list, Pyright complains when I access ObservableList-specific methods.

    Continue reading...

Compartilhe esta Página