I want to see all the variables

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Fri Dec 29 17:46:15 EST 2006


On Fri, 29 Dec 2006 12:04:11 -0800, johnf wrote:

> Ok then how do debug when I have something like "__source"  and I need to
> know what is available for the object?

Outside of a class, objects with two leading underscores are just ordinary
objects with no special behaviour:

>>> __source = 2
>>> __source
2

Objects with a single leading underscore like _source are slightly
special: if you do "from module import *" any names with a single leading
underscore are not imported.

Class attributes with two leading underscores like __source are considered
private to the class, so in general you shouldn't need to know anything
about them. To enforce that, Python mangles the name so it is harder to
reach.

But if/when you do need to get to them, they are easy to get to:

>>> class Spam:
...     __attribute = 2
...
>>> Spam().__attribute
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: Spam instance has no attribute '__attribute'
>>> Spam()._Spam__attribute
2

Notice that Python doesn't generally try to hide "private" attributes:

>>> dir(Spam)
['_Spam__attribute', '__doc__', '__module__']

There are three other underscore conventions in use:

(1) Objects with a single leading underscore like _attribute are private
by convention, but Python doesn't enforce it. Starting an object with a
single underscore is like writing "# Private! Don't touch!" after it.

(2) By convention, if you want to create a name that is the same as a
built-in object without shadowing (hiding) the built-in, put a single
trailing underscore after it like "file_". That's just a style convention
though, you are free to call it FiLE ,or anything else, if you prefer.

(3) Last but not least, class attributes with two leading and trailing
underscores are considered special but public, like __init__ and __repr__.
It is probably a bad idea to invent your own.



-- 
Steven.




More information about the Python-list mailing list