Python Naming Conventions for Variables

Recently in a Python webinar, the topic of discussion was Python naming conventions for variables. When it comes to writing clean and readable code, naming conventions play a crucial role. In this blog post, we will get into the various naming conventions for variables in Python, with a focus on different types of variables including global, boolean, class, private, constant, and instance variables.

1. General Naming Conventions for Variables

General naming conventions for variables are essential for writing clean, readable, and maintainable code. These conventions ensure consistency across codebases and make it easier for developers to understand and collaborate on projects.

Example:

# Good variable naming
user_name = "Alice"
age = 25
print(f"User: {user_name}, Age: {age}")

Output:

User: Alice, Age: 25

You can refer to the below screenshot to see the output.

Python General Naming Conventions for Variables

Following general naming conventions, such as using descriptive names, adhering to case conventions, and avoiding reserved keywords, significantly enhances code clarity. Consistent and meaningful variable names make your code easier to debug, maintain, and share with others.

Read Access Modifiers in Python

2. Naming Conventions for Global Variables

Global variables are variables declared outside of functions or classes and are accessible throughout the entire program. To distinguish them from local variables, it’s common to use a specific naming convention, such as prefixing them with g_ or writing them in UPPERCASE if they are constants.

Example:

# Global variable with a prefix
g_user_count = 5

def increment_user():
    global g_user_count
    g_user_count += 1

increment_user()
print(f"Total Users: {g_user_count}")

Output:

Total Users: 6

You can refer to the below screenshot to see the output.

Python Naming Conventions for Variables Global Variables

Using a consistent naming convention for global variables, such as prefixing them with g_ or writing them in uppercase improves code readability and reduces the risk of naming conflicts. 

Check out How to Use Single and Double Quotes in Python?

3. Boolean Variable Naming Conventions

Boolean variables store True or False values and are often used to represent states or conditions in a program. To make their purpose clear, boolean variable names should start with prefixes like is_has_can_, or should_

Example:

# Boolean variable with a descriptive name
is_authenticated = True

if is_authenticated:
    print("Access granted!")
else:
    print("Access denied!")

Output:

Access granted!

You can refer to the below screenshot to see the output.

Python Naming Conventions for Variables Boolean Variable

Using meaningful prefixes like is_has_, or can_ for boolean variables makes the code more intuitive and easier to understand.

Read Python 3 vs Python 2

4. Class Variable Naming Conventions

Class variables are shared across all instances of a class and are defined within the class but outside any methods. To distinguish them from instance variables, class variables are typically written in UPPERCASE with underscores separating words.

Example:

class Employee:
    # Class variable
    COMPANY_NAME = "TechCorp"

    def __init__(self, name):
        self.name = name

# Accessing class variable
print(f"Company: {Employee.COMPANY_NAME}")

Output:

Company: TechCorp

Using uppercase names for class variables helps differentiate them from instance variables and constants. This convention improves code readability and ensures that the purpose and scope of the variable are clear.

Check out Difference Between “is None” and “== None” in Python

5. Python Private Variable Naming Conventions

In Python, private variables are intended to be used only within the class and are not meant to be accessed directly from outside. To indicate that a variable is private, it is prefixed with a single underscore (_).

Example:

class BankAccount:
    def __init__(self, balance):
        self._balance = balance  # Private variable

    def show_balance(self):
        print(f"Balance: {self._balance}")

account = BankAccount(1000)
account.show_balance()

Output:

Balance: 1000

Using a single underscore (_) prefix for private variables is a convention in Python to indicate that the variable should not be accessed directly outside the class.

Read How to Comment Out a Block of Code in Python?

6. Python ConstantsVariable Naming Conventions

Constants are variables whose values are not meant to change during the execution of a program. In Python, constants are typically defined at the module level and written in UPPERCASE with underscores separating words.

Example:

# Constant variable
MAX_USERS = 100

def check_user_limit(user_count):
    if user_count > MAX_USERS:
        print("User limit exceeded!")
    else:
        print("User limit is within range.")

check_user_limit(105)

Output:

User limit exceeded!

Using uppercase names for constants helps distinguish them from regular variables and signals that their values should not be changed. 

Check out Difference Between {} and [] in Python

7. Python Instance Variable Naming Conventions

Instance variables are unique to each object (instance) of a class and are defined within methods, typically in the __init__ method. They should follow the snake_case naming convention and use descriptive names to indicate their purpose. 

Example:

class Car:
    def __init__(self, make, model):
        self.make = make  # Instance variable
        self.model = model  # Instance variable

    def display_info(self):
        print(f"Car: {self.make} {self.model}")

my_car = Car("Toyota", "Corolla")
my_car.display_info()

Output:

Car: Toyota Corolla

Instance variables should use snake_case and have descriptive names to reflect their purpose. This convention ensures clarity and consistency in the code, making it easier to understand and maintain. 

Read Compare Lists, Tuples, Sets, and Dictionaries in Python

Conclusion

In this article, I helped you to understand Python naming conventions for variables. I explained general naming conventions for variables, naming conventions for global variables, boolean variable naming conventions, class variable naming conventions, Python private variable naming conventions, Python constant variable naming conventions, and Python instance variable naming conventions.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.