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

Alan Gauld alan.gauld at btinternet.com
Tue Jul 28 11:08:52 CEST 2015


On 25/07/15 22:08, boB Stepp wrote:

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

Various others have commented on the use cases for this. I'd just add 
that my solution to using a name that's already used by the language (or 
even already used by my project) is to attach an article prefix  such as 
'my':

Thus instead of using 'type_' I'd use 'my_type' or 'the_type'.

I also do this a lot in parameter lists of functions/methods so:

def someMethod(self, aWidget, aDimension):
     ....

which avoids the common confusion where the parameters are the
same as the names of variables in the calling scope and it
can get confusing as to whether references inside the method
are to parameters or global names.

In particular in class definitions I often use theXXX for a
class attribute name, myXXX for an instance attribute name,
and aXXX for the parameter of a method.

This is not nearly so important in Python because you have to
use self.xxx to get the attribute (and use Class.xxx for
class attributes) but in other OOP languages where self
is not required I find it helps a lot.

I work quite hard to avoid names with dangling underscores because:
1) They look like an error - somebody forgot to type half the name!
2) Depending on font its hard to differentiate single and
    double underscores.
3) They make reading the code aloud (eg over the phone during
     a late night call-out!) much more difficult.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list