Variable names, or identifiers, are an important part of any programming language. In Python, there are some specific rules and conventions for naming variables that developers should follow to write cleaner, more readable code and avoid errors. This guide will provide a comprehensive overview of Python’s rules for variable names, including naming conventions, acceptable and unacceptable names, and best practices.
Table of Contents
Open Table of Contents
- Introduction
- Naming Conventions and Styles
- Acceptable Names - Letters, Numbers, Underscores
- Unacceptable Names - Start with Number or Special Characters
- Case Sensitivity
- Reserved Words to Avoid
- Length Limitations
- Global and Local Variables
- Constants Naming Convention
- CamelCase, snake_case and more
- Best Practices for Naming Variables
- Conclusion
Introduction
Variable names in Python, also known as identifiers, refer to the names given to variables, functions, classes, modules and other objects in Python code. These names are used to label and access the associated objects.
Choosing descriptive, unambiguous and consistent names for variables and other identifiers is crucial for writing understandable and maintainable code in any programming language. Python has some specific rules and conventions to follow when naming identifiers that aim to balance machine-readability with human-readability.
This guide will cover the following topics related to variable naming in Python:
- Naming conventions and styles
- Acceptable names - letters, numbers, underscores
- Unacceptable names - starting with number or special characters
- Case sensitivity
- Reserved words to avoid
- Length limitations
- Global and local variables
- Constants naming convention
- CamelCase, snake_case and more
- Best practices for naming variables
Understanding and following Python’s rules and conventions for naming variables will help programmers write more readable and Pythonic code.
Naming Conventions and Styles
Unlike some programming languages, Python does not enforce strict rules for naming variables and other identifiers. However, developers are encouraged to follow Python’s naming conventions and style recommendations outlined in PEP 8 - Style Guide for Python Code.
The overarching goals for naming identifiers in Python are:
- Readability - names should be descriptive and unambiguous
- Consistency - use the same conventions throughout a module or project
- Brevity yet clarity - find a balance between overly long and overly terse names
- Avoid confusion - do not use names that could confuse the reader
Some key conventions and style recommendations from PEP 8 for naming variables in Python include:
- Use lowercase names separated by underscores for multi-word variable names (snake_case)
- Use descriptive names that reflect the purpose or content of the variable
- Prefer shorter names for local variables, longer names for global variables
- Avoid single letter variable names, except in cases like loop counters
- Class names should be in CamelCase format
- Module and package names should be short, lowercase
- Function names should be lowercase, with underscores
- Constant names should be all uppercase with underscores
These conventions aim to balance human and machine readability for variable names in Python.
Acceptable Names - Letters, Numbers, Underscores
In Python, variable names must start with a letter or underscore, which can be followed by any number of letters, numbers or underscores.
Valid variable names include:
my_variable_name
variable12345
_temp
a
a1
my_long_variable
MY_CONSTANT
Notice that variable names can contain both uppercase and lowercase letters. This follows the case sensitivity rules outlined later.
Including numbers in variable names is allowed, but should generally be avoided in most cases according to the style guidelines. Numbers may be appropriate for some temporary variables, like loop counters.
Underscores can be used to separate words in multi-word variable names for readability. Multiple consecutive underscores are also acceptable.
Unacceptable Names - Start with Number or Special Characters
There are some rules for what is not allowed in Python variable names:
- Names cannot begin with a number. For example,
1var
is invalid. - Names cannot contain special symbols like @, $, % etc. For example,
@count
is invalid. - Names cannot have spaces between words. For example,
my variable
is invalid.
Attempting to use any of these unacceptable names will result in a SyntaxError
in Python.
The only special symbol allowed is a single underscore at the start or within a name. Underscores improve readability for multi-word names.
Case Sensitivity
Python variable names and all identifiers are case sensitive. This means capitalization matters when referencing variables.
For example:
my_var = "Hello"
My_var = "World"
print(my_var) # Prints "Hello"
print(My_var) # Prints "World"
The variable my_var
is distinct from My_var
based on capitalization. Attempting to access a variablename with improper capitalization will result in an error.
This contrasts with languages like JavaScript where variable names are case-sensitive.
Reserved Words to Avoid
There are certain words in Python that are reserved keywords used by the language itself. These cannot be used as variable names.
Some examples of reserved words in Python include:
and del from None True
as elif global nonlocal try
assert else if not while
break except import or with
class False in pass yield
continue finally is raise
def for lambda return
If you try to assign these reserved words as variable names, it will lead to a SyntaxError
.
In addition to these keywords, Python has some built-in constants like True
, False
and None
that cannot be reassigned.
Length Limitations
Python does not explicitly impose a minimum or maximum length for variable names and other identifiers. But there are some practical length limitations:
- Python style guidelines recommend short but descriptive names
- Extremely long names reduce readability
- Most identifiers longer than 30-40 characters become difficult to work with
- Course auto-grader scripts may truncate long names to a fixed length
As a rule of thumb, balance brevity with descriptive names up to 10-20 characters for local variables and 20-40 for global names. Very long names should be avoided for usability.
Global and Local Variables
Based on scope and usage context, Python variables can be classified as global or local:
-
Global variables - Defined at the module level, outside functions and classes. Accessible from anywhere in that module. Should have longer descriptive names.
-
Local variables - Defined inside a function or class. Only accessible within that context. Can have short single word names for brevity.
Here is an example to demonstrate:
# global variable
my_module_var = "module level var"
def my_func():
# local variable
x = 5
print(x)
print(my_module_var) # works
print(x) # errors, x is not defined outside function
The naming conventions may differ slightly for global vs local variables based on scope and context.
Constants Naming Convention
For variables that are intended to remain constant throughout a program, Python style guidelines recommend using all uppercase names with underscores.
For example:
MAX_ITERATIONS = 1000
PI = 3.14
SPEED_LIMIT = 55 #km/h
This capitalized naming convention indicates to the reader that the variable should not change value anywhere in the code.
Attempting to reassign a constant would not lead to an error, but goes against conventions.
CamelCase, snake_case and more
The Python community has adopted several naming styles and conventions for improving readability:
-
snake_case - Variable names with underscores between words (e.g.
my_var
). Recommended for most variables. -
MACRO_CASE - Uppercase variable names with underscores, for constants (e.g.
MAX_WIDTH
) -
CamelCase - Variable words joined together, first letter uppercase (e.g.
MyVariable
). Used for class names. -
CapWords - Multiple words joined with first letter uppercase (e.g.
MyVariableName
). Used for some exceptions. -
lowercase - No capitalization (e.g.
myvariable
). Used for function names. -
single_leading_underscore - Indicates a ‘private’ class attribute (e.g.
_my_var
) -
double_leading_underscore - Triggers name mangling in a class (e.g.
__my_var
)
These naming conventions help improve the readability and usability of variable names in Python.
Best Practices for Naming Variables
To summarize the key points, here are some best practices to follow when naming variables and other identifiers in Python:
- Use descriptive, unambiguous names that reflect the purpose of the variable
- Leverage snake_case convention for multi-word local variable names
- Use MACRO_CASE for constants that should remain unchanged
- Follow CamelCase convention for class names
- Avoid overly short or single letter names, except where convention allows (e.g.
i
for indexes) - Do not use Python reserved words or built-in names like
True
,False
- Avoid naming variables after Python standard library modules (e.g.
math
,csv
) - Use longer, more descriptive names for modules and global variables
- Shorten local variable names for brevity and scope-limiting
- Do not start names with a number or special symbol (except
_
) - Leverage multiple underscores for ‘private’ class attributes
- Use CapWords convention for exceptions
- Maintain consistency in naming conventions across a module or project
Adhering to these variable naming rules and conventions will ensure you are writing clean, readable and Pythonic code. With meaningful names for variables and other identifiers, both humans and machines can better understand the code.
Conclusion
Variable names are an important element for writing understandable and maintainable Python code. Unlike some languages, Python does not impose strict naming rules, but has several widely adopted conventions and best practices.
This guide summarized the key rules and conventions for naming variables or identifiers in Python code:
- Use descriptive, lowercase names like snake_case or CamelCase
- Avoid starting names with numbers or special characters
- Capitalization matters due to case sensitivity
- Do not use Python reserved words or built-ins as names
- Distinguish global and local variables via naming conventions
- Use CAPS for constants, single underscore for ‘private’ attributes
- Keep local variables short, globals longer and descriptive
- Overall, aim for readable, unambiguous and consistent naming
By following Python’s style guidelines and variable naming rules, programmers can create more readable, reusable and Pythonic code. Meaningful names serve self-documenting purposes to understand code flow and intent. This allows programmers to better maintain and collaborate on Python projects and modules.