Search code examples
pythonattributespython-typing

Type hint for attribute that might not exist


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.


Solution

  • The answer currently appears to be "You can't".

    I've started a discussion thread for this in the Python Typing repo, which may get more visibility.