0. Python Naming Conventions
In Python, using consistent naming conventions is crucial for writing clean, readable, and maintainable code. These conventions are widely accepted within the Python community and are described in PEP 8, the official Python style guide. Following these guidelines helps ensure that your code is easily understandable and maintainable by others (and yourself) over time.
1. General Rules for Identifiers
1.1 Case Sensitivity
Python is case-sensitive, meaning Variable
and variable
are two different identifiers. Hence, it’s important to follow consistent case conventions.
1.2 Allowed Characters
Python identifiers can contain:
- Letters (
a-z
,A-Z
) - Digits (
0-9
) - Underscores (
_
)
However, identifiers must not start with a digit.
1.3 Avoid Special Characters
Symbols like $
, %
, &
, etc., are not allowed in Python identifiers.
2. Variable and Function Naming
2.1 Lowercase with Underscores (snake_case
)
-
Variables and function names should be written in all lowercase letters, with words separated by underscores if necessary.
Examples:
user_name = "John"def calculate_total_price(quantity, price):return quantity * price -
Avoid using capital letters or camelCase for variables and functions. Consistent use of
snake_case
ensures readability.
2.2 Avoid Single-character Variable Names (unless it’s a loop counter)
- Single-letter variables like
x
,y
, orz
should only be used for short, non-complex variables like indices or loop counters.
2.3 Avoid Shadowing Built-in Functions
-
Python has several built-in functions, such as
list
,str
, andint
. Avoid naming your variables or functions after these, as it may lead to bugs or confusion.Example of poor practice:
list = [1, 2, 3] # Shadows the built-in list function
2.4 Descriptive Names
Use meaningful names for variables and functions that clearly describe their purpose.
Example:
def calculate_area_of_rectangle(width, height): return width * height
3. Constants
Uppercase with Underscores (UPPER_CASE
)
-
Constants should be named in all uppercase letters, with words separated by underscores. By convention, constants are defined at the top of the module or script.
Examples:
MAX_CONNECTIONS = 10PI = 3.14159
4. Class Naming
CapWords (CamelCase)
-
Class names should use the
CapWords
convention, also known as camel case. Each word starts with a capital letter, with no underscores between words.Examples:
class DataProcessor:passclass UserProfile:pass -
Classes that inherit from built-in types should have meaningful names that do not conflict with the standard Python types (e.g., avoid naming your class
List
,Dict
, etc.).
5. Method and Attribute Naming in Classes
Lowercase with Underscores (snake_case
)
-
Method and instance attribute names should follow the same convention as function names: lowercase with underscores.
Examples:
class Car:def start_engine(self):passdef get_mileage(self):return self.mileage
6. Private Methods and Attributes
6.1 Single Underscore Prefix (_method_name
)
-
A single underscore before a method or variable name indicates that it is intended for internal use (non-public), though it is still accessible from outside the class.
Example:
class DataProcessor:def _load_data(self):pass
6.2 Double Underscore Prefix (__method_name
)
-
Double underscores indicate name-mangling, which is used to prevent subclasses from overriding methods unintentionally. However, this practice is generally discouraged unless necessary.
Example:
class Car:def __calculate_fuel_efficiency(self):pass
7. Module and Package Naming
7.1 Lowercase with Underscores (snake_case
)
-
Module names should be short, all lowercase, and, if needed, words can be separated by underscores.
Examples:
math_operations.py
data_loader.py
7.2 Package Naming
-
Package names should follow the same rules as module names, but using underscores is generally avoided unless necessary.
Examples:
analytics
machinelearning
8. Global Variable Naming
Use sparingly
Global variables should be used sparingly. If they are needed, follow the same rules as constants: uppercase with underscores.
Example:
GLOBAL_TIMEOUT = 300
9. Function Arguments
9.1 Descriptive Names
Function arguments should have descriptive names that indicate their role in the function. Avoid using generic names like x
, y
, or data
unless the purpose is clear in the context.
Example:
def send_email(recipient_email, subject, body): pass
9.2 Keyword Arguments
-
Use descriptive names for keyword arguments to improve code clarity.
Example:
def connect_to_server(hostname, timeout=30, use_ssl=True):pass
10. Exceptions Naming
CapWords
-
Exceptions should also follow the
CapWords
naming convention, and names should typically end with the wordError
.Examples:
class FileNotFoundError(Exception):passclass InvalidUserInputError(Exception):pass
11. Boolean Variables
Prefix with is_
, has_
, or can_
Boolean variables and function names should be descriptive, often prefixed with is_
, has_
, or can_
, which clarifies that the value returned is True
or False
.
Examples:
is_valid = Truehas_permissions = False
def can_drive(age): return age >= 18
12. Naming for Test Functions
Use Descriptive Names for Test Functions
When naming test functions, use descriptive names that explain what the test is verifying.
Example:
def test_addition_of_two_numbers(): pass
def test_user_can_login(): pass
13. Avoid Overusing Abbreviations
-
Avoid excessive abbreviations unless they are commonly understood. While abbreviations can make code shorter, they often reduce readability.
Example:
- Instead of
calc_val()
, usecalculate_value()
.
- Instead of
14. Special Variables and Methods
Python has a set of special methods and variables that start and end with double underscores, also known as “dunder” methods. These should be used only for their intended purposes.
Examples:
class MyClass: def __init__(self): pass
def __str__(self): return "MyClass instance"
Avoid creating your own names that begin with double underscores, as it might conflict with Python’s special methods.