Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Python instance variables with __dict__- Is it wrong?

Tags:

python

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__?

like image 744
sans Avatar asked Jan 18 '11 18:01

sans


2 Answers

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.

like image 85
unode Avatar answered Sep 23 '22 14:09

unode


That footnote is in reference to the __dict__ attribute of a module. The __dict__ attribute of an object carries no such warning (documentation).

like image 24
Ray Avatar answered Sep 19 '22 14:09

Ray