Solved: Question about idiomatic use of _ and private stuff.

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Feb 24 00:01:23 EST 2007


On Fri, 23 Feb 2007 23:17:32 -0500, Steven W. Orr wrote:

> On Friday, Feb 23rd 2007 at 11:12 -0500, quoth Steven W. Orr:
> 
> =>I understand that two leading underscores in a class attribute make the 
> =>attribute private. But I often see things that are coded up with one 
> =>underscore. Unless I'm missing something, there's a idiom going on here.
> =>
> =>Why do people sometimes use one leading underscore?
> 
> I found the answer. 

Not quite.


> It turns out that if you say:
> 
> import foo 
> 
> then you get access to all of the attributes that are not mangled. A 
> single leading underscore does not cause mangling.
> 
> If you say 
> 
> from foo import _fooa, _foob, 
> 
> then the import will fail because the _ is used only by the import to 
> decide that you shouldn't see _fooa or _foob.

Incorrect.

Let's try it. From the shell:

$ cat data.py
fear = "The chief weapon of the Spanish Inquisition"
_parrot = "A green bird"
__spam = "A nasty treat"


And then from Python:

>>> from data import fear, _parrot, __spam
>>> fear
'The chief weapon of the Spanish Inquisition'
>>> _parrot
'A green bird'
>>> __spam
'A nasty treat'

Python only ignores _names when you call "from module import *".

Here are the underscore rules:

(1) In the interactive interpreter, the name "_" is automatically set to
the result of the last command.

(2) Names with a SINGLE lead underscore are ignored when you say "from
module import *". They are imported if you ask for them directly, and in
the normal "import module" form.

(3) Class attributes, but not other objects, with TWO leading underscores
have their names mangled by Python. E.g. Parrot.__method is mangled to
Parrot._Parrot__method.

(4) Names with two leading underscores and two trailing underscores may be
reserved for special methods (e.g. __init__, __str__, etc.) and objects
(e.g. __all__ in packages, __name__, etc.). While Python doesn't prohibit
you from creating your own methods with leading and trailing underscores,
it is discouraged.

(5) If you want to give an object a name which clashes with a built-in,
the convention is to append a single TRAILING underscore to the name (e.g.
print_).


Hope that's clear now.



-- 
Steven.




More information about the Python-list mailing list