Python Programming Style Guide

 

Naming Conventions

Statement StructurePython Style GuideComments

When choosing names for items in your program, Python doesn't care what you use so long as you avoid the reserved words. But a good naming convention can help to produce source code that is easy to read and understand. This section describes the naming convention that should be followed for the course.

Camel Case Notation. Unless otherwise indicated, the names of all multi-word identifiers must use the camel case notation. That is, the first letter of each word, except possibly the first, should be capitalized. For example: listLength, studentNames, StudentFile.

Identifier Length. All identifiers should be of sufficient length to provide a descriptive name. You do not have to create excessively long names, but shorter names including single character ones are typically not very descriptive. Note, that some single letter variable names can be used when appropriate to the given problem. Examples include loop variables (i.e. i, j) or to represent Cartesian coordinates (i.e. x, y).

Variable Names

Variables and constants should have meaningful names that relate to their contents. The names for all user-defined variables should:

  • Begin with a lower case letter.
  • Consist of multiple words, when necessary, using the camel case notation.
   response, firstName, currentEntry, listLength

All non-trivial constant values in a program should be assigned meaningful names that:

  • Consist of all uppercase letters.
  • Have multiple words separated with an underscore.
   MAX_FRIENDS, PI, TAX_RATE, LOWER_LIMIT, MAX_LINE_LENGTH

Constants often describe a limit within the program. In these cases, it is appropriate to use the prefix MIN or MAX in conjunction with the name.

Function Names

Functions should have descriptive meaningful names that relate to their purpose; The name should give some idea as to what the function does. As with variables, the names for all user-defined functions should:

  • Begin with a lower case letter.
  • When necessary, consist of multiple words using the camel case notation.
   getEntry(), displayError(), isEmpty(), findName(), printCalendar()

There are any number of conventions that can be used when naming functions. One common approach is to include a verb at the beginning of the name to express the implied action ("do this").

   printAddress(), getLength(), findMaxValue(), isFull()

Class Names

The simplest and shortest names should be reserved for class names. Classes should be named with short, generic nouns that reflect their contents. They should start with a capital letter and follow the camel case notation if the name consists of multiple words.

   Bag, Date, FileReader, Histogram, SearchTree, HashTable

Some classes may be private to the module in which they are defined. In which case, they are only meant to be used within that module. In this case, the class name should be preceded with a single underscore.

   _ArrayIterator, _ListNode, _TreeNode

While this does not prevent a programmer from importing the class, it is a simple notation to help flag the improper use of a private class.

Data Attributes

Data attributes generally should not be accessible from outside the class itself. Most object-oriented programming languages provide a mechanism to hide or protect the data attributes from outside access in order to enforce the abstraction provided by the class. Python does not provide a means to protect attributes to prevent their misuse. But we can use our own notation to flag an attribute as being private to the given class. We then have to trust the user of the class to not attempt a direct access to the private attributes. The names of all private data attributes should:

  • Follow the naming convention used with variables.
  • Prepend a single underscore to the attribute name to flag it as being private to the class in which it is defined.
   self._julianDay, self._xCoord, self._yCoord.

For naming data attributes of storage classes, see the special section on storage classes.

Class Methods

User-defined Methods. The naming scheme used for user-defined methods should follow that of user-defined functions as described above.

Operator Methods. Some methods define special Python operators, in which case you must use the name prescribed by Python. The naming convention used by Python for all of the operator methods consists of two underscores preceding the operator name and two underscores following the name.

   __add__(), __mul__(), __lt__(), __float__(), __str__()

Helper Methods. Some classes may also include helper methods. Helper methods are like any other method, but they are commonly used in the implementation of a class to allow for the subdivision of a larger method into smaller parts or to reduce code repetition. Helper methods are not meant to be used outside the class in which they are defined. Thus, the naming scheme used for helper methods should follow that used with private data attributes (precede their name with a single underscore).

   _getIndex(), _isValidDate(), _reduceToNormalForm()

Modules

The names used for Python modules and program files should be descriptive but not excessively long. Python source files will be named with a .py extension.

Warning Warning

Filenames should not contain blank spaces or other special characters.

Naming Hints

The most important criterion when choosing a name is: how easily can another programmer (not just yourself) understand the program? If understanding a name was not important, we could just name all variables a, b, c, etc. Here are some additional pointers on how to choose names in a program:

  • Names should be pronounceable. You should opt to use untruncated, long names over using names that are not pronounceable. As a "rule of mouth", if you cannot read the name out loud, it's not a good name. For example, use groupId instead of grpId, nameLength instead of namlen, powersOfTwo instead of pwrsOf2.
  • Abbreviate with care. Abbreviations always carry the risk of being misunderstood. For example, does termProcess mean terminateProcess or terminalProcess? Abbreviations are usually also hard to pronounce (for example, nxtGrp). Use only commonly known abbreviations, like the avg, id, size, and count. As a general rule of thumb, you should only abbreviate a name if it saves more than three characters.
  • Do not use names whose only difference is capitalization. Python is case sensitive, so the name groupID is different from the name groupId. If two names in the same program only differ in capitalization, typographical mistakes can create errors that are very difficult to track down.
  • Boolean variable and function names should state a fact that can be true or false: done. In many cases, this is easy to achieve with the inclusion of "is" in the name: printerIsReady, queueIsEmpty, or simply done. Note how naturally this reads:
if listIsEmpty :
  addItem( item )
  • The more important an object is, the more care should go into choosing its name. In a short function, a variable like ok is probably fine since "what is OK" is probably easily determined from the context. However, this is most likely not the case with class attributes or method and function arguments.



Statement StructurePython Style GuideComments
Print -- Recent Changes
Page last modified on April 23, 2012, at 10:54 AM