Name mangling vs qualified access to class attributes

Marco Paolieri paolieri at gmail.com
Thu Dec 15 05:36:18 EST 2016


Hi all,

Thank you for the feedback. So, to recap, reasons to use name mangling
'self.__update(iterable)' rather than qualified access
'Mapping.update(self, iterable)' are:


1. Qualified access stops working when class 'Mapping' is renamed
(at compile-time) or its name is reassigned at runtime.

Honestly, I wouldn't worry about the first case: if I rename a class,
fixing qualified accesses within the class itself is just a matter of
refactoring.  Instead, when another class is assigned to the name
'Mapping' (in the scope where it was defined), qualified access breaks
at runtime, while looking up methods through 'self' still works.


2. Method lookup through 'self' allows subclasses or instances to
override mangled names.

This should be extremely rare. After all, mangled names are meant to
avoid overrides.


For me, the takeaway is that it's always better to invoke methods on
'self', rather than passing 'self' yourself. As Guido said about the
drawbacks of having methods see each other in their scopes:

"m1(self) and self.m1() [would be] equivalent.  That's evil, because
it opens up a meaningless choice between alternative (and the m1(self)
notation is inferior, because it doesn't look in base classes)."

https://mail.python.org/pipermail/python-dev/2000-November/010598.html


Best,
-- Marco



More information about the Python-list mailing list