Skip to content
Home » Blog » Python Naming Conventions for Developers: A Complete Cheat Sheet

Python Naming Conventions for Developers: A Complete Cheat Sheet

Introduction

Let’s talk about something simple but crucial in Python—Python naming conventions.

Why does this matter? Because clear, consistent names make your code easier to read, understand, and maintain. When variables and functions have meaningful names, you (and others) can quickly grasp what the code is doing. But if names are inconsistent or vague, the code becomes a frustrating puzzle to decipher.

Python follows an official style guide called PEP 8, which lays out clear rules for naming things properly. Sticking to these guidelines makes your code look professional, polished, and team-friendly—whether you’re working alone or as part of a team.


Must Read


Python Naming Conventions: Best Practices for Developers

An infographic-style table comparing Python naming conventions. It includes six categories: Variables, Functions, Classes, Constants, Modules, and Packages. Each row highlights best practices, incorrect naming styles, and examples. The table uses color coding—green for best practices, red for mistakes, and blue for headers.
Python Naming Styles at a Glance A quick reference table for Python naming conventions. Learn the correct way to name variables, functions, classes, constants, modules, and packages—with real examples!

General Python Naming Rules

Python is case-sensitive, which means myVariable, MyVariable, and MYVARIABLE are all different. That’s why it’s important to follow consistent naming rules to avoid confusion.

When naming variables, functions, or classes, always use meaningful and descriptive names. A name like total_price is way better than tp because it tells you exactly what it represents.

Also, avoid using reserved keywords as names. These are special words that Python already uses for its own functions and commands, so if you try to use them, you’ll get errors.

Python Reserved Keywords (Avoid These!)

Here’s a list of Python’s reserved keywords—you can’t use these as variable or function names:

False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, 
finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, 
while, with, yield

If you accidentally use one of these as a name, Python won’t understand what you’re trying to do!

Variable Naming Conventions in Python

Python has specific rules and best practices for naming variables. If you follow them, your code will be clear, readable, and easy to understand. If you ignore them, your code can quickly become confusing, even to yourself!

1. Use snake_case for variable names

Python follows snake_case, which means:

  • All letters should be lowercase.
  • Words should be separated by underscores (_) instead of spaces.

Correct examples:

user_name = "Alice"
total_price = 99.99
order_count = 5

Each of these names clearly describes what the variable stores.

Incorrect examples:

userName = "Alice"    # Uses camelCase (not recommended in Python)
TotalPrice = 99.99    # Uses PascalCase (only used for class names)
orderCount = 5        # Again, camelCase is not Pythonic

In Python, snake_case is the standard, while camelCase is more common in JavaScript and Java.

2. Avoid single-letter variables (except for temporary values)

A variable should describe what it stores. If you use names like x or y, it’s impossible to know what they mean just by looking at them.

Bad example:

x = "John"
y = 30

If someone else sees this code, they won’t know what x and y represent. Even you might forget after a few days!

Good example:

customer_name = "John"
customer_age = 30

This makes it immediately clear what each variable means.

The only time single-letter variables make sense is when they’re used temporarily—like in loops.

Example where single-letter variables are okay:

for i in range(5):  
    print(i)  # 'i' is just a counter, so it's fine here

3. Keep variable names concise but descriptive

A name should be long enough to describe what it stores but not too long that it becomes annoying to type.

Good examples:

total_price = 50.75
user_email = "alice@example.com"

Bad examples:

tp = 50.75                      # Too short—unclear
total_price_of_all_items = 50.75  # Too long—unnecessary detail

The key is balance. You don’t want names that are too vague or too long.

Common Naming Mistakes

1. Using unclear abbreviations

Abbreviations can make code hard to understand, especially if they aren’t obvious.

Bad examples:

usrnm = "JohnDoe"   # What does 'usrnm' mean?
amt_pd = 100.0      # 'amt_pd' is not immediately clear

Good examples:

username = "JohnDoe"
amount_paid = 100.0

Unless an abbreviation is very common (like id for “identifier” or url for “Uniform Resource Locator”), avoid it.

2. Mixing camelCase with snake_case

Python sticks to snake_case for variables. Mixing different styles makes code inconsistent and harder to read.

Bad examples (camelCase, not Pythonic):

userName = "Alice"
orderTotal = 250

Good examples (proper snake_case):

user_name = "Alice"
order_total = 250

If you ever see camelCase, that’s common in JavaScript, but in Python, it’s not the standard.

3. Starting names with numbers or special characters

Variable names cannot start with a number or special character (except for underscores).

Invalid examples:

2nd_attempt = "Retry"  # Starts with a number (invalid)
@price = 99.99         # Uses a special character (invalid)

Valid alternative:

second_attempt = "Retry"
price = 99.99

Why This Matters

Following these rules will make your code:

  1. Easy to read – You’ll know what each variable means without guessing.
  2. Consistent – If everyone follows the same rules, working with code is much easier.
  3. Error-free – You won’t run into weird problems caused by incorrect names.

When writing Python, always think:

  • Does my variable name describe what it stores?
  • Is it easy to read?
  • Am I following Python’s snake_case standard?

If the answer to all three is yes, you’re doing it right!

Function Naming Conventions in Python

When naming functions in Python, clarity and consistency are key. A well-named function makes it immediately clear what it does, making your code easier to read and maintain. Let’s go over the best practices and common mistakes to avoid.

A side-by-side comparison of Python function and variable naming best practices. The left side (green) lists correct names like calculate_total() and user_age, while the right side (red) shows incorrect names like CalcTotal() and usrAg. The third column explains why the correct naming is preferred, emphasizing Python's snake_case convention and readability best practices.
Python Function & Variable Naming Best Practices

How to Name Functions in Python

1. Use snake_case for function names

Python follows the snake_case style for function names, just like variable names. This means:

  • All letters should be lowercase.
  • Words should be separated by underscores (_).

Correct examples:

calculate_total()  
get_user_data()  
send_email_notification()  

Each function name describes an action clearly.

Incorrect examples:

CalculateTotal()   # PascalCase (used for class names, not functions)
getUserData()      # camelCase (common in JavaScript, not Python)
Get_User_Data()    # Mixed styles (not consistent)

Python prefers lowercase with underscores for function names. Using PascalCase or camelCase is not Pythonic.

2. Use action words to describe what the function does

A function name should start with a verb that clearly indicates its purpose. This makes it easy to understand what the function does.

Good examples:

fetch_customer_records()  # "fetch" tells us it's retrieving data
validate_user_input()     # "validate" means it's checking input
calculate_discount()      # "calculate" implies performing a computation

Bad examples:

data_processing()   # What kind of processing?  
helper_function()   # Too vague—what does it help with?  
info()             # What kind of info? Too generic  

A good function name removes ambiguity so that no extra comments are needed to understand what it does.

Function Naming Mistakes to Avoid

1. Using ambiguous or generic names

A function name should clearly indicate its purpose. Generic names like process_data() or handle_input() don’t provide enough information about what they actually do.

Bad examples:

process_data()  # What kind of processing?  
handle_input()  # What does it do with the input?  

Better alternatives:

normalize_text_data()  # Clearly states it's for text data  
validate_form_input()  # Tells us it's checking form input  

Tip: If a function name makes you ask questions about what it does, it’s not specific enough!

2. Inconsistent casing

Python functions should always use snake_case. Mixing different naming styles can confuse readers and make your code harder to follow.

Bad examples:

GetUserData()      # PascalCase (not for functions)
getUserData()      # camelCase (not Pythonic)
Get_User_Data()    # Mixed styles (not consistent)

Correct alternative:

get_user_data()  # Consistent with Python conventions  

Why Function Naming Matters

Following these naming rules makes your code:

  • Readable – Other developers (or even your future self) can instantly understand what a function does.
  • Consistent – If every function follows the same pattern, it’s easier to navigate large codebases.
  • Maintainable – Good naming reduces the need for extra comments or documentation.

Whenever you name a function, ask yourself:

  • Does this name clearly describe what the function does?
  • Is it easy to read and understand?
  • Am I following Python’s snake_case standard?

If yes, then you’ve got a well-named function!

Class Naming Conventions in Python

When naming classes in Python, following the right conventions makes your code clear, structured, and easy to understand. If you name classes incorrectly, your code can look messy and be harder to maintain. Let’s go over the right way to do it and the common mistakes to avoid.

A hierarchical tree diagram showcasing Python class naming conventions. At the top, 'UserProfile' is written in PascalCase as a class name. Below it, two methods, 'get_user_info()' and 'update_profile()', follow the snake_case convention. At the bottom, attributes '_password' (protected) and '__config' (private) are displayed, following Python's naming rules. The diagram uses rectangles with color-coding: blue for the class, green for methods, and red for attributes. Shortened arrows clearly indicate relationships without overlapping the rectangles.
Python Class Naming Hierarchy – Best Practices

Proper Way to Name Classes

1. Use PascalCase

In Python, class names should always follow PascalCase, which means:

  • Each word starts with an uppercase letter.
  • No underscores or spaces between words.

Correct examples:

class UserProfile:
    pass

class OrderProcessor:
    pass

class DataAnalyzer:
    pass

Each class name clearly describes what the class represents.

2. Keep Class Names Descriptive and Singular

A class represents a single entity or concept, so its name should be singular.

Good examples:

class Customer:
    pass  # Represents one customer

class Order:
    pass  # Represents a single order

Bad examples:

class Customers:  # ❌ Class names should be singular
    pass

class Orders:  # ❌ This suggests multiple orders, which isn’t ideal
    pass

Common Class Naming Errors

1. Using lowercase or snake_case

Python follows PascalCase for class names. Lowercase or snake_case is incorrect.

Wrong examples:

class userprofile:  # ❌ All lowercase (not recommended)
    pass

class user_profile:  # ❌ Uses snake_case (wrong for classes)
    pass

Correct alternative:

class UserProfile:
    pass

2. Adding Unnecessary Prefixes

You don’t need extra prefixes like Cls or C before class names. Python already knows it’s a class, so these prefixes don’t add value.

Wrong examples:

class ClsUserProfile:  # ❌ "Cls" is unnecessary
    pass

class COrderProcessor:  # ❌ No need to add "C" before the name
    pass

Correct alternative:

class UserProfile:
    pass

Why This Matters

Following proper class naming conventions:

  • Makes your code look professional and easy to read.
  • Keeps everything consistent so others (and your future self) can understand the code quickly.
  • Avoids confusion when working with different Python structures.

When naming classes, always check:

  • Am I using PascalCase?
  • Is the name singular and descriptive?
  • Did I avoid unnecessary prefixes?

If you can say yes to all three, your class names are spot on!

How to Name Constants in Python

In Python, constants are values that should never change while your program runs. Unlike variables, which can be updated, constants are meant to stay the same.

Even though Python doesn’t have a built-in way to enforce constants (like const in JavaScript or final in Java), the convention is to use UPPER_CASE_WITH_UNDERSCORES to show that a value is a constant.

1. Use all uppercase letters with underscores

To clearly indicate that a value is a constant, use UPPER_CASE_WITH_UNDERSCORES.

Correct examples:

MAX_ATTEMPTS = 5  
API_KEY = "1234567890abcdef"  
DEFAULT_TIMEOUT = 30  

Each name is clear, easy to read, and follows Python’s convention.

Incorrect examples:

maxAttempts = 5       # Uses camelCase (not Pythonic)
apiKey = "1234567890" # Not in uppercase
defaulttimeout = 30   # No underscores, hard to read

Using anything other than uppercase with underscores makes it look like a regular variable, which can confuse other developers (or even you later on!).

2. Declare constants at the top of a file

It’s a good practice to define all constants at the beginning of your script or module. This makes them easy to find and update if needed.

Example of correct placement:

# constants.py
BASE_URL = "https://example.com"
PI = 3.14159
MAX_USERS = 1000

Then, in your main script, you can import these constants instead of redefining them:

from constants import BASE_URL, PI, MAX_USERS  

print(BASE_URL)  # Output: https://example.com

This keeps your code clean and avoids accidental modifications to important values.

3. Keep constant names descriptive

Even though constants shouldn’t change, they should still have meaningful names.

Good examples:

DATABASE_URL = "localhost:5432"
JWT_SECRET_KEY = "supersecurekey"

Each of these clearly describes what the value is used for.

Bad examples:

DB = "localhost:5432"  # Too vague
SECRET = "supersecurekey"  # What kind of secret?

If someone else looks at your code, they should immediately understand what each constant does without having to guess.

Naming Mistakes with Constants

Using lowercase instead of uppercase

Constants should always be in UPPER_CASE_WITH_UNDERSCORES. If you write them in lowercase, they look like regular variables.

Incorrect:

max_attempts = 5   # Looks like a normal variable
api_key = "abcdef" # Easy to mistake for a changeable value

Correct:

MAX_ATTEMPTS = 5
API_KEY = "abcdef"

Not defining constants separately

Some people define constants inside functions, which makes them look like regular variables and allows accidental modification.

Incorrect:

def get_api_key():
    api_key = "1234567890abcdef"  # Looks like a local variable
    return api_key

This makes it hard to know that api_key is actually a constant value.

Correct:

API_KEY = "1234567890abcdef"

def get_api_key():
    return API_KEY  # Clearly a constant

By defining API_KEY at the top of the file, it’s clear that this value isn’t meant to change.

Why Follow These Rules?

Using UPPER_CASE_WITH_UNDERSCORES and placing constants at the top of the file makes your code:

  • Easier to read – Anyone can tell which values are constants.
  • More maintainable – If you need to update a constant, you only change it in one place.
  • Less error-prone – You won’t accidentally change an important value mid-program.

Whenever you declare a constant, ask yourself:

  • Is the name clear?
  • Whether it’s in uppercase?
  • Is it placed at the top of the file or in a config module?

If the answer is yes, you’re doing it right!

Module and Package Naming Conventions in Python

When naming modules and packages in Python, following the correct conventions helps keep your project organized, easy to navigate, and maintainable. Let’s go through the best practices for naming both.

A directory-style diagram illustrating Python package and module naming conventions. At the top, 'ecommerce/' is displayed as the main package. Below, three sub-packages ('orders/', 'users/', 'payments/') are shown. Each sub-package contains a module named using snake_case: 'order_processing.py', 'user_auth.py', and 'payment_gateway.py'. The diagram uses rectangles with color coding: blue for the main package, green for sub-packages, and red for modules. Shortened arrows avoid overlapping rectangles, ensuring a clear hierarchical structure.
Python Module and Package Naming Guide

Naming Python Modules

A module in Python is just a .py file that contains code (functions, classes, or variables) that can be imported and reused.

Best Practices for Module Names

  • Use all lowercase letters.
  • Separate words with underscores if necessary.

Examples:

data_processing.py
user_auth.py
file_manager.py

Each of these names clearly describes what the module does while following Python’s naming standards.

What to Avoid in Module Names

  1. Spaces or special characters
data processing.py  # ❌ Invalid (spaces are not allowed)
user@auth.py        # ❌ Invalid (special characters are not allowed)

Fix: Use underscores instead: data_processing.py.

2. Mixing PascalCase or camelCase

DataProcessing.py  # ❌ Invalid (PascalCase is used for class names)
userAuth.py        # ❌ Invalid (camelCase is not Pythonic)

Fix: Stick to data_processing.py or user_auth.py.

Naming Python Packages

A package in Python is a directory that contains one or more modules and a special __init__.py file.

Best Practices for Package Names

  • Use all lowercase letters.
  • Do NOT use underscores (Python prefers package names without them).

Examples:

mypackage/
datatools/
userauth/

These names are simple, clear, and follow Python’s standard for package naming.

What to Avoid in Package Names

  1. Using underscores or spaces
my_package/   # ❌ Avoid underscores in package names
data tools/   # ❌ Spaces are not allowed

Fix: Use mypackage/ or datatools/.

2. Using PascalCase

DataTools/   # ❌ Avoid PascalCase in package names

Fix: Use datatools/ instead.

Why These Naming Conventions Matter

  • Consistency → When everyone follows the same naming rules, Python projects stay organized and easy to read.
  • Avoids import errors → Using proper names prevents issues when importing modules and packages.
  • Follows Python’s official guidelines → The Python community and PEP 8 recommend these standards.

By following these simple rules, you’ll write clean, professional, and maintainable Python code!

Special Naming Conventions in Python

Python has some special naming rules for certain types of variables and methods. These conventions help indicate how a variable or function should be used.

Private and Protected Variables

Python doesn’t have true private variables like some other languages (such as Java or C++). However, there is a convention to indicate that a variable is meant to be private or protected.

1. Private Variables (Prefix with _)

If a variable name starts with a single underscore (_), it’s considered private. This means that it’s not meant to be accessed directly from outside the class.

Example:

class User:
    def __init__(self, name, password):
        self.name = name
        self._password = password  # Private variable

user = User("Alice", "secure123")
print(user.name)       # Works fine
print(user._password)  # Not recommended, but still accessible

Even though _password is private, Python does not actually prevent you from accessing it. It’s just a convention, meaning you shouldn’t access it directly.

2. Protected Variables (Prefix with __)

If a variable name starts with double underscores (__), it’s considered protected. Unlike private variables, Python applies name mangling to these variables. This means Python renames them internally to prevent accidental access.

Example:

class User:
    def __init__(self, name, config):
        self.name = name
        self.__config = config  # Protected variable

user = User("Bob", "Admin Settings")
print(user.name)          # Works fine
print(user.__config)      # This will cause an AttributeError

Why does print(user.__config) fail?
Because Python renames __config to something like _User__config. You can still force access like this:

print(user._User__config)  # Works, but strongly discouraged

This is Python’s way of saying, “If you really want to access this, you can—but you probably shouldn’t.

Key takeaway:

  • _single underscore → A variable is private by convention, but still accessible.
  • __double underscore → A variable is name-mangled to prevent accidental access, but it can still be accessed with tricks.

Dunder (Double Underscore) Methods

Dunder methods (short for “Double UNDERscore“) are special methods that Python automatically recognizes. These methods start and end with double underscores (__). They are used in object-oriented programming (OOP) to define how objects behave.

1. __init__ Method (Constructor)

This method is called automatically when a new object is created. It initializes the object.

Example:

class User:
    def __init__(self, name):
        self.name = name  # This runs when a new User object is created

user1 = User("Charlie")  
print(user1.name)  # Output: Charlie

The __init__ method runs automatically every time you create a new instance of the class.

2. __str__ Method (String Representation)

The __str__ method controls how an object is converted into a string.

Example:

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

    def __str__(self):
        return f"User: {self.name}"

user2 = User("David")
print(user2)  # Output: User: David

Without __str__, printing an object would just show something like <__main__.User object at 0x123456>, which isn’t useful.

Why These Naming Conventions Matter

  1. Private and protected variables help prevent accidental changes to important data.
  2. Dunder methods let you control how objects behave in different situations.
  3. Following these rules makes your code more readable and professional.

By using _private, __protected, and dunder methods, you write code that is easier to understand and maintain.

Bonus: Python Naming Conventions Cheat Sheet (Quick Reference)

This quick reference guide summarizes the most important naming rules in Python. Following these conventions will help keep your code clean, readable, and professional.

ElementNaming StyleExample
Variablesnake_caseuser_name
Functionsnake_caseget_user_data()
ClassPascalCaseUserProfile
ConstantUPPER_CASEMAX_RETRIES
Modulelowercase_with_underscoresdata_processing.py
Packagelowercasemypackage
Private Variable_single_leading_underscore_password
Protected Variable__double_leading_underscore__config
Dunder Methodsdouble_underscore__init__

Conclusion

Following Python naming conventions isn’t just about writing code that works—it’s about making your code readable, maintainable, and professional. By using the right naming rules, you make it easier for yourself and other developers to understand and collaborate on your projects.

Here’s a quick recap of the key takeaways:

  • Use snake_case for variables and functions.
  • Follow PascalCase for class names.
  • Keep constants in UPPER_CASE.
  • Name modules and packages in lowercase.
  • Use underscores (_, __) to indicate private and protected attributes.
  • Follow PEP 8 guidelines to ensure consistency across your codebase.

By sticking to these rules, you’re writing Python code that’s not just correct but also clean and professional. Want to explore more best practices? Check out the official PEP 8 style guide for in-depth recommendations.

FAQs on Python Naming Conventions

1. Why is following Python naming conventions important?

Using proper naming conventions makes your code easier to read, understand, and maintain. It also ensures consistency, especially when working in a team, and helps avoid naming conflicts with Python’s built-in functions and libraries.

2. What is the difference between private (_var) and protected (__var) variables?

A private variable (single underscore _var) is a convention, meaning it signals that the variable is for internal use, but it can still be accessed.
A protected variable (double underscore __var) triggers name mangling, which makes it harder to access directly, helping prevent accidental modifications.

3. Should I always use snake_case for function names?

Yes, Python’s PEP 8 guidelines recommend using snake_case for function names (e.g., get_user_data()). This keeps your code consistent and readable. However, class names should be written in PascalCase (e.g., UserProfile).

4. Can I use Python’s reserved keywords as variable names?

No, reserved keywords like class, def, and return cannot be used as variable names because they have special meanings in Python. If you need a similar name, you can modify it slightly (e.g., class_name instead of class).

External Resources on Python Naming Conventions

If you want to deepen your understanding of Python naming conventions and best practices, here are some great resources to check out:

PEP 8 – The Official Python Style Guide

  • The go-to reference for writing clean and professional Python code.

Python Reserved Keywords (Official Docs)

  • A complete list of Python’s reserved words that you should avoid using as variable names.

Python Code Style Checker (flake8)

  • A useful tool to automatically check your code for PEP 8 violations.

Black – The Uncompromising Code Formatter

  • A Python tool that formats your code to follow PEP 8 guidelines automatically.

These resources will help you write cleaner, more readable Python code while following industry standards.

About The Author

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Rating