[Tutor] _ vs. _name vs. __name vs. name_ vs. __name__ usages

Zachary Ware zachary.ware+pytut at gmail.com
Sat Jul 25 23:58:32 CEST 2015


On Saturday, July 25, 2015, boB Stepp <robertvstepp at gmail.com
<javascript:_e(%7B%7D,'cvml','robertvstepp at gmail.com');>> wrote:
>
> 5) __name__ is meant to be used only by the creators of Python for
> their special built-in methods, such as __init__, __new__, etc.


Everything up to this point was pretty accurate. You're only half
right with this one, though; __dunder__ names are ones that you should only
use when hooking into the "magic" of the interpreter. That is, you should
not define your own __dunder__ names, but feel free to use ones that have
been defined by the implementation and documented as the way to do
something. For example:

class Spam:
    def __init__(self, value):
        self.value = value

    def __getitem__(self, key):
        return self.value

assert Spam(42)['eggs'] == 42

__getitem__ is the documented method to implement to allow instances of
your class to be indexed like a list or dict.

Are my understandings above correct or flawed?
>
> For (3), it seems to me that one would normally be able to use the
> simpler _name construction from (2).  What would be a best-practice
> example of when name mangling *should* be used?


I have yet to ever see a place where name mangling was warranted. I have
been severely annoyed by it before, though. To make a particular class work
the way I wanted it to, I had to subclass it and explicitly override a
couple of mangled names.  In my opinion, name mangling should never be used
unless overriding the value will set your CPU aflame.

Likewise, it seems that normally (4) should never be needed, though I
> have a feeling that I have seen something in tkinter recently that
> suggests some exceptions, but I cannot (yet) bring it to mind.


There are a couple of methods in tkinter that accept an 'in_' keyword
argument, where in Tcl it is documented as 'in', which is a Python
keyword.  In code that's not interfacing with something else that uses a
Python keyword, it's usually best to just find a different name.

And for (5), surely I should never violate this one?  It seems that in
> some future edition of Python they might add any particular __name__
> that I might try to use presently in their future version of Python
> (however miniscule that possibility might actually be).
>

Right, don't make up your own __dunder__ names.

Hope this helps,

--
Zach
(On an iPad)


-- 
Sent from Gmail Mobile


More information about the Tutor mailing list