Request for help on naming conventions

Terry Hancock hancock at anansispaceworks.com
Mon Jun 13 19:20:14 EDT 2005


On Monday 13 June 2005 03:59 am, Steven D'Aprano wrote:
> Are there any useful naming conventions for modules, classes and functions?
> 
> For instance, should I name functions as verbs and classes as nouns?

Hmm. Okay, here's a few I use:

Classes are generally: Capitalized  or CapWords  and I use nouns.
Unless it's a "mix-in" in which case, I use adjectives.  This mirrors
usage in the Zope sources, BTW.

Method names are either: funkyCaps (Zope uses this) or
lower_case_with_underscores.

I use verb names for methods and functions with very few exceptions.

I use nouns or occasionally adjectives for attributes.

Constants or enumeration values are ALLCAPS or ALL_CAPS, and
usually I define them within a namespace with a descriptive, all lower
case name (a trivial class).  The enumeration is usually abbreviated,
but would be an adjective, e.g.:

color.RED

I use *plural* names for lists and tuples, but singular names for
mappings.  This is so that I can use the singular in the loop:

for book in books:
    pass

But I use single character variables in list comprehensions (and
generators, except I haven't used them yet):

late_books = [b for b in books if b.duedate < datetime.now()]

I also use single-character names in highly mathematical code:

def dot_product(a,b):
    return a.x*b.x + a.y*b.y + a.z*b.z

But if a variable is going to be used more than about 20 lines
away from where it is defined, I use a descriptive word instead.

I like to use Capital or CapWords for modules, too, although I'm
beginning to wonder about that practice.

I really hate redundancy like this:

Topic.create_topic()

and usually prefer:

Topic.create()

which of course means, I have to qualify things a lot in my code.
This has never been an issue, but if it did, I would just introduce
an intermediary like this ("_" for "."):

Topic_create = Topic.create


After that, it's kind of case-by-case.  Do read PEP 8, too, of
course.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list