5. Notes on Python Coding Style#

The most definitive reference on this is PEP 8 – Style Guide for Python Code.

5.1. Restrictions on characters used in names#

TL;DR: Mostly lower-case letters and digits.

  • The names of Python variables (including the names of functions) must start with a letter and only contain letters, digits, and the underscore _ (typed as “shift-dash”). That is, no dashes (-), spaces or other punctuation.

  • The names of files containing Python modules must follow the above restrictions (apart from the period in the suffix “.py” of course) because these names are used as variable names in import statements.

  • The names of notebook files have just a little more flexibility: they can also include hyphens. That is, they should only contain letters, digits, underscores and hyphens; no spaces or other punctuation. (Again, apart from the period in the suffix “.ipynb”.)
    Aside: this is roughly the same rule as for web-site addresses.
    Although you can get away with some other characters in some situations, that will run into problems in situations like cross-referencing to a notebook from another notebook, posting on a web-site, and using a notebook as a section in a Jupyter Book.

5.2. Naming style#

In this book names are sometimes a description formed from several words, and since spaces are forbidden, this is generally done by using snake_case; either omit the space entirely or—if it helps readbility—put an underscore where you would like to have a space, but may not. For example, an error estimate might be in a variable errorestimate or error_estimate. (Another popular style is to capitalize the first letter of each new word, as with errorEstimate.)

It is commonly recommended to avoid upper-case letters, but I often make an exception when the mathematical convention is to use upper-case, as with the names of matrices.

An exception to this is naming Classes as introduced in Classes, Objects, Attributes, Methods: Very Basic Object-Oriented Programming in Python, and Exceptions as in Exceptions and Exception Handling; for those, the convention is to is use CapWords.