Skip to content

Rules for Variable Naming (Identifiers) in Python

Updated: at 01:23 AM

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

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:

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:

Some key conventions and style recommendations from PEP 8 for naming variables in Python include:

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:

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:

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:

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:

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:

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:

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.