Private methods

I

Ian Kelly

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__.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top