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

boB Stepp robertvstepp at gmail.com
Sat Jul 25 23:08:03 CEST 2015


After having a long discussion with my wife on her user requirements,
I am convinced that an OO approach is required.  Which is just as well
as that has been one of my next areas of learning to do.  I am
currently reading "Python 3 Object Oriented Programming" by Dusty
Phillips, which so far seems to be a reasonably good text.  This has
led me to the subject line topics.

>From my understandings to date:

1) A single underscore is used conventionally for a "throw-away"
variable, such as a loop index for which the index value is not
actually used in a subsequent calculation.

2) _name is used inside class methods to indicate that the
programmer's intention is that this name should only be accessed
internally by that particular class.  Other supposedly "adult" Python
programmers will attempt to respect this original intent if they use
my code.

3) __name invokes Python's name mangling mechanism.  The intent of
this usage is to not allow subclasses of the class containing __name
to access this name, and to add additional emphasis to future users of
my code that this name is meant to be strictly hands-off.

4) name_ is used when one is "forced" to use one of Python's reserved
words as a name.

5) __name__ is meant to be used only by the creators of Python for
their special built-in methods, such as __init__, __new__, etc.

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?

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.

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

Thanks!
boB

-- 
boB


More information about the Tutor mailing list