Reputation: 20296
PEP 526 introduced syntax for variable annotations, that can be added on an instance variable even when the value is not defined.
class BasicStarship:
captain: str = 'Picard' # instance variable with default
damage: int # instance variable without default
But when I list the instance variables, the one without value is not listed:
starship = BasicStarship()
dir(starship) #doesn't return 'damage' field
How can I get all instance variable, including the ones without value?
Upvotes: 1
Views: 124
Reputation: 45742
__annotations__
shows it:
>>> starship.__annotations__
{'captain': <class 'str'>, 'damage': <class 'int'>}
A dict containing annotations of parameters. The keys of the dict are the parameter names, and 'return' for the return annotation, if provided.
Although, note, from your link:
[T]he value-less notation
a: int
allows one to annotate instance variables that should be initialized in__init__
or__new__
.
So, you should be setting it anyway if you're going to do that, in which case it will show up in dir
.
Upvotes: 1