[Poll] Private variables
Christian Tanzer
tanzer at swing.co.at
Sun Sep 16 03:44:59 EDT 2001
"Tim Peters" <tim_one at email.msn.com> wrote:
> > 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.
When was this documentation added? I don't remember reading that (back
in 1.5.x times; of course, my brain might just have chosen to
selectively ignore it).
Feature or bug, it still is an example of feature interaction waiting
to spring surprises on you.
> 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
> interfere.
I understand the difficulty. I still think it would have been better
to just use a different (and documented) mangling scheme for class
names starting with a single underscore (like ___A_beep <shudder>).
> 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>.
My use of `__` names isn't motivated by privacy. The `__` names work
well to allow each class in the hierarchy to have its own unique
variables if it chooses so -- that is handy for some design patterns.
That this variables are open for inspection is a bonus, IMHO.
My consequence is to never use `_Foo` class names. Too bad, that that
means that some classes might be imported by `from X import *` when
I'd rather they wouldn't.
Some-features-are-warts-even-if-documented-ly y'rs
Christian
--
Christian Tanzer tanzer at swing.co.at
Glasauergasse 32 Tel: +43 1 876 62 36
A-1130 Vienna, Austria Fax: +43 1 877 66 92
More information about the Python-list
mailing list