Python’s naming rules and conventions
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.
- Rules are specifications that we MUST follow
- 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
- A name only consists of characters from three groups: digits (
0-9
), letters (a-z
andA-Z
), and underscores (_
) - A name cannot start with a digit
- 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:
- For now, you don’t have to remember all of these keywords. You will remember them as you progress.
- Python distinguishes between lowercase and uppercase. Thus,
firstname
,FirstName
, andFIRSTNAME
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 ofName
- 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 ofgrossProfit
orGrossProfit
. - Should be meaningful and easy to remember. Ex:
interest_rate
instead ofr
orir
. - Should have a reasonable length. Ex:
sales_apr
instead ofsales_data_for_april
- Avoid names of popular functions and modules. Ex: avoid
print
,math
, orcollections
.
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