If I want to access the list of instance variables of an object, I can call myObject.__dict__.keys()
. I want to use this attribute to print out all instance variables of an object. I am hesitant to do this because __dict__
is a "secret" attribute, and I do not understand what this footnote means.
So is it wrong to use myObject.__dict__
?
What the footnote means is that you shouldn't try to access __dict__
directly but instead check if the feature/behavior you want is available.
So instead of doing something like:
if "__some_attribute__" in obj.__dict__:
# do stuff
you should instead do:
try:
obj.some_action_i_want_to_do(...)
except AttributeError:
# doesn't provide the functionality I want
The reasons for this are because different objects might provide different internal references to a certain action but still provide the desired output.
If you want to list the "internals" for the sake of debugging and inspecting the current object, then dir()
is the right way to do it.
That footnote is in reference to the __dict__
attribute of a module. The __dict__
attribute of an object carries no such warning (documentation).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With