Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 351
MarcellPerger Avatar asked Dec 17 '25 02:12

MarcellPerger


1 Answers

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.

like image 99
Chris Withers Avatar answered Dec 19 '25 21:12

Chris Withers