Underscore data hiding (was python development practices?)

Barry A. Warsaw barry at zope.com
Thu Nov 1 02:46:24 EST 2001


>>>>> "MF" == Martijn Faassen <m.faassen at vet.uu.nl> writes:

    MF> The double underscore is required for name mangling, but I
    MF> don't really like the name mangling; it gets in the way. I
    MF> just want to give the programmer a hint that some attribute is
    MF> private, and I use a single underscore for this, and many
    MF> Python programmers with me.

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:

-------------------- snip snip --------------------
class A:
    def __init__(self):
        self._my_private_counter = 0

    def countup(self):
        self._my_private_counter += 1
        print self._my_private_counter

class B(A):
    def __init__(self):
        A.__init__(self)
        self._my_private_counter = 10

    def countdown(self):
        self._my_private_counter -= 1
        print self._my_private_counter

>>> b = B()
>>> b.countup()
11   # huh, why isn't this 1?

class A:
    def __init__(self):
        self.__my_private_counter = 0

    def countup(self):
        self.__my_private_counter += 1
        print self.__my_private_counter

class B(A):
    def __init__(self):
        A.__init__(self)
        self.__my_private_counter = 10

    def countdown(self):
        self.__my_private_counter -= 1
        print self.__my_private_counter

>>> b = B()
>>> b.countup()
1    # ah that's better!
-------------------- snip snip --------------------

IOW, B's designer shouldn't have to know anything about A's private
interface in order to be correctly implemented.  Name mangling
preserves the integrity of A's private API.

Of course, B's designer must know about A's inherited (i.e. protected)
API in order to be correctly implemented.  In that situation, many
different conventions exist.  My own personal one is to prefix
protected API attributes with a single underscore (and document them
;).

-Barry



More information about the Python-list mailing list