16

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

1
  • 4
    You might(?) prefer the vars(myObject) stylistically, but that's orthogonal to your question. It gives the same dict. Commented Jan 18, 2011 at 19:29

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

But dir() only gives the names; __dict__ also gives the objects themselves.
6

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

1 Comment

There are alike warnings for objects when accessors, metaclasses, or slots are used. Exceptions are so cheap in Python that they are used to end iteration in generators.
4

You could use dir function to list all attributes of an object.

Comments

3

Using it for things like printing out members for debugging should be fine. But if that's all you're doing, check out pretty print.

http://docs.python.org/library/pprint.html

The main problem with __dict__, is it violates the implied visibility rules of objects that python has.

4 Comments

__dict__ is hackery. It's powerful and dangerous, and you don't need it at all for programming. That's why. That it violates visibility is just one part of it.
Thank you for pointing out pprint. I always wondered if there was an easy way to emulate iPython-style collection printing.
This __dict__ issue seems like a bit of a rabbit hole but I'd like to understand it better. What do you mean by implied visibility rules?
The problem with __dict__ is that it leads to the idea that obj.__dict__['x'] is the same as obj.x, which is completely wrong. The difference is that obj.x invokes descriptors but __dict__ doesnt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.