Underscore data hiding (was python development practices?)
Tim Peters
tim.one at home.com
Mon Nov 5 20:20:58 EST 2001
[Barry A. Warsaw]
> FWIW, the double-leading-underscore-no-trailing-double-underscore name
> mangling rule wasn't added specifically for data hiding. It was so
> that a class that was designed to be subclassed could have a namespace
> that subclasses couldn't accidently trample on:
[Toby Dickenson]
> Interestingly, I often find that that the chosen mangling scheme
> doesnt achieve that design goal. The scheme mangles the class name
> into the underscore-stripped attribute name, which offers zero
> protection if your base classes and subclasses have the same name.
>
> Does this happen often? A common structure (for me, anyway) is to have
> modules BaseWidget, FooWidget, and BarWidget, all of which define a
> class Widget.
And then what? That is, having a million classes all named Widget isn't a
problem, unless you go on to define Yet Another Widget class using one of
the existing Widgets as a (direct or indirect) base class. But you didn't
say that's what you do, so I'm not sure how your example illustrates your
point.
Before Guido implemented this, the "what if a subclass and class have the
same name?" conflict was discussed on c.l.py:
[Guido, long ago]
> Actually, I would spell it out in the docs, so whoever writes the base
> class that uses private variables can decide whether they will want to
> prtoect against this. I showed a simple way to do this already:
>
> class _RealSpam:
> ...long class definition using __spam all over the place...
> Spam = _RealSpam
Then a Spam derived from this Spam mangles private names in a different way.
I can't guess whether I'd be "happy enough" with that in practice, though,
as the problem it's trying to address has never bit me.
the-class-that-is-named-is-not-the-true-class-ly y'rs - tim
More information about the Python-list
mailing list