Naming and usage

Constants are used to define a set of values the program relies on, such as the default configuration filename.

A good practice is to gather all the constants in a single file in the package. That is how Django works, for instance. A module named settings.py provides all the constants as follows:

# config.py 
SQL_USER = 'tarek' 
SQL_PASSWORD = 'secret' 
SQL_URI = 'postgres://%s:%s@localhost/db' % ( 
    SQL_USER, SQL_PASSWORD 
) 
MAX_THREADS = 4 

Another approach is to use a configuration file that can be parsed with the ConfigParser module, or another configuration parsing tool. But some people argue that it is rather an overkill to use another file format in a language such as Python, where a source file can be edited and changed as easily as a text file.

For options that act like flags, a common practice is to combine them with Boolean operations, as the doctest and re modules do. The pattern taken from doctest is quite simple, as shown in the following code:

OPTIONS = {}

def register_option(name):
return OPTIONS.setdefault(name, 1 << len(OPTIONS))

def has_option(options, name):
return bool(options & name)

# now defining options
BLUE = register_option('BLUE')
RED = register_option('RED')
WHITE = register_option('WHITE')

This code allows for the following usage:

>>> # let's try them 
>>> SET = BLUE | RED 
>>> has_option(SET, BLUE) 
True 
>>> has_option(SET, WHITE) 
False

When you define a new set of constants, avoid using a common prefix for them, unless the module has several independent sets of options. The module name itself is a common prefix.

Another good solution for option-like constants would be to use the Enum class from the built-in enum module and simply rely on the set collection instead of the binary operators. Details of the enum module usage and syntax were explained in the Symbolic enumeration with enum module section of Chapter 3Modern Syntax Elements - Below the Class Level.

Using binary bit-wise operations to combine options is common in Python. The inclusive OR (|) operator will let you combine several options in a single integer, and the AND (&) operator will let you check that the option is present in the integer (refer to the has_option function).

Let's discuss public and private variables in the following section.