Python’s naming rules and conventions

Tue Nguyen
2 min readApr 13, 2022

--

There are only two hard things in Computer Science: cache invalidation and naming things.

(Phil Karlton)

When writing a program, we often have to give names to many things such as variables, functions, classes, and modules. Thus, it is crucial to learn the rules and conventions.

  1. Rules are specifications that we MUST follow
  2. Conventions are more like suggestions of best practices by experienced programmers and are widely accepted by the community. Thus, we are not required to follow, but we SHOULD.

Remarks: For now, we only focus on variable names.

Naming rules

There are three rules when naming a variable

  1. A name only consists of characters from three groups: digits (0-9), letters (a-z and A-Z), and underscores (_)
  2. A name cannot start with a digit
  3. A name cannot coincide with one of Python’s reserved words. Reserved words or keywords are words that have special meaning to Python (see the list below for the complete list)
False       class       finally     is          return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise

Remarks:

  1. For now, you don’t have to remember all of these keywords. You will remember them as you progress.
  2. Python distinguishes between lowercase and uppercase. Thus, firstname, FirstName, and FIRSTNAME are different.

Example 1: valid names

age
num_jobs
file_name
_xyz

Example 2: invalid name

warnings! # contains a special character !
4oceans # starts with a digit
break # coincides with break keyword

Naming convention

Here are some best practices to follow when naming.

  • Use all lowercase. Ex: name instead of Name
  • One exception: class names should start with a capital letter and follow by lowercase letters.
  • Use snake_case convention (i.e., separate words by underscores, look like a snake). Ex: gross_profit instead of grossProfit or GrossProfit.
  • Should be meaningful and easy to remember. Ex: interest_rate instead of r or ir.
  • Should have a reasonable length. Ex: sales_apr instead of sales_data_for_april
  • Avoid names of popular functions and modules. Ex: avoid print, math, or collections.

Example 1: names having good styles

first_name
cum_gpa
class_rank

Example 2: names having bad styles

fn # ambiguous
FirstName # not snake case
print # name of a popular function
os # name of a popular module
sys # name of a popular module
salary_data_of_10000_households # too long

Navigation

Previous article: Python variables and assignments
Next article: Python typing systems

--

--

Tue Nguyen
Tue Nguyen

Written by Tue Nguyen

Former data scientist. MSc student in quantitative economics. Love sharing data science stuff.