- Naming Convention in Python [With Examples]
- Naming Conventions in Python
- General Python Naming Conventions
- Names to Avoid in Python
- Python Programming Naming Styles
- Python Global Variable Naming Conventions
- Python Class Naming Conventions
- Python Class Method Naming Convention
- Python Class Attribute Naming Convention
- Python Class File Naming Convention
- Python Class Instance Naming Convention
- Python Object Naming Conventions
- Python Variable Naming Conventions
- Python Function Naming Convention
- Conclusion
Naming Convention in Python [With Examples]
This tutorial explains everything about naming conventions in Python. We will get to know Python global variable naming conventions, object naming conventions in Python, how to name a class in Python, etc. Everything we will see here with practical examples.
Naming Conventions in Python
Python naming conventions are a set of guidelines established in PEP8, Python’s official style guide. These guidelines set the standard for how we name variables, functions, classes, modules, and other identifiers.
While these conventions are not enforced by the Python interpreter, adhering to them is considered a mark of good coding practice. They help make your code self-explanatory, more readable, and maintainable, thereby increasing the overall quality of your code.
In this guide, we will delve deeper into these conventions, illustrating each with practical examples, helping you to write cleaner, more ‘Pythonic’ code.
General Python Naming Conventions
The most fundamental rules in Python’s naming conventions are:
- Names are case-sensitive.
- Names cannot start with a digit.
- Names can contain letters, numbers, and underscores.
Names to Avoid in Python
Never use characters ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single-character variable names. These can be easily mistaken in certain fonts for ‘1’ (one), ‘0’ (zero), and ‘|’ (pipe), respectively.
Reserved words in Python cannot be used as variable names. These include ‘for’, ‘while’, ‘if’, ‘else’, etc.
Python Programming Naming Styles
There are several styles used in Python:
- Snake Case: Snake case has all words lowercase separated by underscores. This is primarily used for function and variable names.
Example: user_name , my_function
- Pascal Case: Pascal case is similar to camel case but starts with a capital letter. This is used for class names in Python.
Example: ClassName , MyClass
- Camel Case: Camel case has the first letter of each word capitalized except for the first word. This is not commonly used in Python.
Example: myVariable , isInstance
Here’s a tabular representation of various case types:
Case Type | Description | Example |
---|---|---|
Snake Case | All words lower case separated by underscores | my_function , user_input |
Pascal Case | The first letter of each word is capitalized except the first word | MyClass , AnotherClass |
Camel Case | First letter of each word is capitalized except the first word | myVariable , isInstance |
Upper Case with Underscores | All letters are upper case and words are separated by underscores | MAX_OVERFLOW , TOTAL |
By sticking to these naming conventions, your Python code will be more readable, maintainable, and in line with community standards.
Python Global Variable Naming Conventions
In Python, a variable declared outside of a function or a block of code is referred to as a global variable. These global variables can be accessed by any function in the program.
When it comes to naming global variables in Python, the PEP8 style guide provides clear guidelines.
As a convention, global variables should be named following the snake_case style. This means that if your variable name consists of multiple words, they should be in lowercase and separated by underscores.
# Correct way global_variable = "I'm a global variable"
That said, it’s important to note that using global variables should generally be avoided as they can lead to confusing code and may be prone to errors.
In cases where you need constants (i.e., variables whose values won’t change), Python’s convention is to use uppercase letters and separate words with underscores. These are technically global variables as well, but they have different use cases.
# Correct way MAX_SIZE = 100 PI_VALUE = 3.14159
As we see above, constants such as MAX_SIZE and PI_VALUE are in uppercase, emphasizing that they should not be changed.
Python Class Naming Conventions
In Python, the naming convention for classes is PascalCase, which means that the first letter of each word is capitalized and there are no underscores between words.
# Correct way class MyNewClass: pass # Incorrect way class my_new_class: pass
Python Class Method Naming Convention
Methods in Python classes should be named using snake_case. This means that all words should be in lowercase and separated by underscores.
class MyClass: def my_method(self): pass
Python Class Attribute Naming Convention
Similar to methods, class attributes (variables defined in the class) should also be named using snake_case in Python.
class MyClass: my_attribute = 10
Python Class File Naming Convention
When naming Python files that contain classes, you should follow the snake_case convention as well. This helps make it clear and readable, especially when importing modules.
Here’s an example: my_python_file.py
Python Class Instance Naming Convention
When creating instances of a class (also known as objects) in Python, it’s recommended to use snake_case as well. This keeps it consistent with the rest of your variables.
class MyClass: pass my_class_instance = MyClass()
Python Object Naming Conventions
Objects in Python are instances of a class that you’ve defined. The naming convention for Python objects follows the same rules as that for regular variables.
When you create an object, the name should be in snake_case, which means all words are in lowercase, and words are separated by underscores. The name should be descriptive, making it clear what the object represents. Avoid using Python keywords and function names as object names.
Let’s consider a class named Car :
class Car: def __init__(self, color, make, model): self.color = color self.make = make self.model = model
When creating an object (or instance) of the Car class, the name should adhere to the snake_case convention. Here’s an example:
# Correct way my_car = Car('red', 'Toyota', 'Corolla') # Incorrect way MyCar = Car('red', 'Toyota', 'Corolla') myCar = Car('red', 'Toyota', 'Corolla')
The example above, my_car clearly communicates that this is an instance of a car and follows the snake_case naming convention.
Python Variable Naming Conventions
In Python, variable names follow the snake_case naming convention as per the PEP8 style guide. This means that all words in the name are in lowercase, and each word is separated by an underscore.
# Correct way my_variable = 10 # Incorrect way myVariable = 10 MyVariable = 10
Here are a few more guidelines when naming variables in Python:
- Variable names should be descriptive and meaningful to make the code more readable and understandable.
For instance, if you have a variable holding the number of users, num_users would be a clear and understandable choice.
# Incorrect 123abc = "Hello" @name = "Hello" # Correct abc123 = "Hello" name = "Hello"
- Avoid using Python keywords and function names as variable names. For instance, don’t name your variable list , dict , str , print , etc.
# Incorrect list = [1, 2, 3] # Correct my_list = [1, 2, 3]
Python Function Naming Convention
In Python, function names follow the snake_case naming convention as per the PEP8 style guide. This means all words should be in lowercase, and each word is separated by an underscore.
# Correct way def my_function(): pass # Incorrect way def MyFunction(): pass def myFunction(): pass
Here are a few more guidelines when naming functions in Python:
- Descriptive Names: Function names should be descriptive and indicate the function’s purpose. This improves readability and understanding of the code.
# Correct way def calculate_average(): pass # Incorrect way def func1(): pass
In the example above, calculate_average gives a clear indication of what the function is supposed to do, while func1 doesn’t provide any meaningful context.
- Avoid Using Python Keywords and Function Names: Avoid naming your function the same as Python keywords or existing function names. This can lead to unwanted behavior and confusion.
# Incorrect def print(): pass # Correct def print_custom_message(): pass
- Use Action Words: Since functions usually perform an action, it’s a good practice to start the function name with a verb. This immediately gives an idea of what action the function performs.
# Correct def get_total(): pass # Correct def print_report(): pass
Conclusion
Adhering to Python’s naming conventions is a crucial aspect of writing clean, professional, and efficient code. It makes your code much more readable and understandable, not just to others, but to your future self as well.
Python’s naming conventions, outlined in the PEP8 style guide, provide clear directions for how identifiers such as variables, functions, classes, methods, modules, and other elements should be named. This includes practices such as using snake_case for variables and functions, PascalCase for classes, and UPPER_CASE_WITH_UNDERSCORES for constants.
However, it’s essential to remember that these conventions are guidelines rather than strict rules enforced by the language. They are designed to provide a common structure for all Python programmers, promoting code consistency and readability across the Python community. In certain situations, there may be reasons to deviate slightly from these conventions, such as when maintaining legacy code or when a team has agreed upon specific alterations for their project.
In the end, the key goal behind using these conventions is to write code that is easy to read, understand, and maintain. By using clear, descriptive names, you can make your code self-explanatory, reducing the need for excessive comments and making it easier for others (and yourself in the future) to quickly grasp the purpose of different parts of your code.
You may also like the following Python tutorials:
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.