Private methods

Ian Kelly ian.g.kelly at
Thu Nov 1 23:45:22 CET 2012

On Tue, Oct 9, 2012 at 5:51 PM, Steven D'Aprano
<steve+comp.lang.python at> wrote:
> On Tue, 09 Oct 2012 11:08:13 -0600, Ian Kelly wrote:
>> I tend to view name mangling as being more for avoiding internal
>> attribute collisions in complex inheritance structures than for
>> designating names as private.
> Really? I tend to view name mangling as a waste of time, and complex
> inheritance structures as something to avoid.

Name mangling is also useful for object tagging.  Suppose you have
object A that is passed object B and needs to track some data
concerning object B, but does not need a strong reference to B.  One
solution is to use a weak-key dictionary, but this relies upon B being
hashable, and I find it neater to just store the data on B itself.
The problem is that whatever name you use might conflict with an
existing attribute belonging to B.

class Tagger(object):

    def tag(self, taggee):
        taggee.__tag = some_tag_data

One of the curious ramifications of Python's name-mangling system is
that even though the attribute above is being set on some arbitrary
object, the mangling that is applied is in any case that of the class
Tagger.  Thus the mangled attribute name ends up being "_Tagger__tag",
which is unlikely to cause a conflict.

There are some disadvantages to tagging.  One is that you can't tag
objects of built-in types.  Another is that you can't tag instances of
classes with __slots__.  I tend to view the latter as another reason
to avoid using __slots__.

More information about the Python-list mailing list