[Poll] Private variables

Tim Peters tim_one at email.msn.com
Sun Sep 16 08:23:48 CEST 2001

[Christian Tanzer]
>     Python 2.1 (#1, May  2 2001, 18:27:26)
>     [GCC] on linux2
>     Type "copyright", "credits" or "license" for more information.
>     >>> class _A :
>     ...   __beep = 1
>     ...
>     >>> class A(_A) :
>     ...   __beep = 2
>     ...
>     >>> class B(A) :
>     ...   __beep = 3
>     ...
>     >>> dir (_A)
>     ['_A__beep', '__doc__', '__module__']
>     >>> dir(A)
>     ['_A__beep', '__doc__', '__module__']
>     >>> dir(B)
>     ['_B__beep', '__doc__', '__module__']
>     >>>
> The name mangling of `__bar` names misbehaves if the class name starts
> with a single underscore. To be able to use `__bar` names safely one
> has to avoid `_Foo` class names.
> This is the only example of accidental feature interaction in Python
> that I'm aware of.

It's not an accident:  the compiler goes out of its way to remove leading
underscores from class names while mangling, and this behavior is documented
in section 5.2.1 (Identifiers -- Private name mangling) of the Ref Man.

Suppose it didn't do this.  Then the mangled name in _A would be __A_beep,
and in A would (still be) _A_beep.  How then in A would you be able to
access _A's version of beep?  If you typed __A_beep within the scope of A,
it would get mangled to _A__A_beep:  the point of the rule is so that a
mangled name never ever "looks like" a private name, so that in turn you can
always do the mangling by hand (when needed) and not have the compiler

You could protest that if you *wanted* to access _A's beep from within A you
never would have made it a private name to begin with -- but Guido knows you
don't really mean that, so Python makes sure you can cheat despite your
idealistic intentions <wink>.

python-is-an-anti-terrorist-language-ly y'rs  - tim

More information about the Python-list mailing list