[Python] Type hint for attribute that might not exist

Discussão em 'Python' iniciado por Stack, Março 19, 2025.

  1. Stack

    Stack Membro Participativo

    How do I do a type hint for attribute that might not exist on the object in Python?

    For example:

    class X:
    __slots__ = ('attr',)
    attr: int # either int or doesn't exist - what do I put here?


    So, concretely:

    >>> x = X()
    >>> x.attr
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AttributeError: 'X' object has no attribute 'attr'
    >>> x.attr = 1
    >>> x.attr
    1


    ...but there are also cases where __slots__ isn't involved.

    Continue reading...

Compartilhe esta Página