Open In App

Python Naming Conventions

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python, known for its simplicity and readability, places a strong emphasis on writing clean and maintainable code. One of the key aspects contributing to this readability is adhering to Python Naming Conventions. In this article, we’ll delve into the specifics of Python Naming Conventions, covering modules, functions, global and local variables, classes, and exceptions. Each section will be accompanied by runnable code examples to illustrate the principles in action.

What is Naming Conventions?

Naming conventions in Python refer to a set of rules and guidelines for naming variables, functions, classes, and other entities in your code. Adhering to these conventions ensures consistency, readability, and better collaboration among developers.

Python Naming Conventions

Here, we discuss the Naming Conventions in Python which are follows.

  • Modules
  • Variables
  • Classes
  • Exceptions

Modules

Modules in Python are files containing Python definitions and statements. When naming a module, use lowercase letters and underscores, making it descriptive but concise. Let’s create a module named math_operations.py.

In this example, code defines two functions: add_numbers that returns the sum of two input values, and subtract_numbers that returns the difference between two input values. To demonstrate, if you call add_numbers(5, 3) it will return 8, and if you call subtract_numbers(5, 3) it will return 2.

Python3




def add_numbers(a, b):
    result = a + b
    print(f"The sum is: {result}")
    return result
 
def subtract_numbers(a, b):
    result = a - b
    print(f"The difference is: {result}")
    return result
 
# Example usage:
add_result = add_numbers(5, 3)
subtract_result = subtract_numbers(5, 3)


Output

The sum is: 8
The difference is: 2



Variables

Globals variable should be in uppercase with underscores separating words, while locals variable should follow the same convention as functions. Demonstrating consistency in naming conventions enhances code readability and maintainability, contributing to a more robust and organized codebase.

In below, code defines a global variable GLOBAL_VARIABLE with a value of 10. Inside the example_function, a local variable local_variable is assigned a value of 5, and the sum of the global and local variables is printed.

Python3




GLOBAL_VARIABLE = 10
 
def example_function():
    local_variable = 5
    print(GLOBAL_VARIABLE + local_variable)
 
# Call the function to print the result
example_function()


Output

15



Classes

Classes in Python names should follow the CapWords (or CamelCase) convention. This means that the first letter of each word in the class name should be capitalized, and there should be no underscores between words.This convention helps improve code readability and consistency in programming projects.

In this example, the class “Car” has an initializer method (__init__) that sets the make and model attributes of an instance. The “display_info” method prints the car’s make and model.

Python3




class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model
 
    def display_info(self):
        print(f"{self.make} {self.model}")


Exceptions

Exception in Python names should end with “Error,” following the CapWords convention. it is advisable to choose meaningful names that reflect the nature of the exception, providing clarity to developers who may encounter the error.

In this example, below code creates an instance of CustomError with a specific error message and then raises that exception within a try block. The except block catches the CustomError exception and prints a message

Python3




class CustomError(Exception):
    def __init__(self, message):
        super().__init__(message)
 
# Creating an instance of CustomError
custom_exception = CustomError("This is a custom error message")
 
# Catching and handling the exception
try:
    raise custom_exception
except CustomError as ce:
    print(f"Caught a custom exception: {ce}")


Output

Caught a custom exception: This is a custom error message



Importance of Naming Conventions

The importance of Naming Conventions in Python is following.

  • Naming conventions enhance code readability, making it easier for developers to understand the purpose and functionality of variables, functions, classes, and other code elements.
  • Consistent naming conventions contribute to code maintainability. When developers follow a standardized naming pattern, it becomes more straightforward for others to update, debug, or extend the code.
  • Naming conventions are especially important in collaborative coding environments. When multiple developers work on a project, adhering to a common naming style ensures a cohesive and unified codebase.
  • Well-chosen names can help prevent errors. A descriptive name that accurately reflects the purpose of a variable or function reduces the likelihood of misunderstandings or unintentional misuse.

Conclusion

In conclusion, By emphasizing readability, supporting collaborative development, aiding error prevention, and enabling seamless tool integration, these conventions serve as a guiding principle for Python developers. Consistent and meaningful naming not only enhances individual understanding but also fosters a unified and coherent coding environment. Embracing these conventions ensures that Python code remains robust, accessible, and adaptable, ultimately promoting best practices in software development.



Similar Reads

File Naming Conventions | Significance and Tips for SEO
When it comes to Search Engine Optimization (SEO), every detail matters. Everything from tags to the structure of your content plays a role in determining how visible your website is on search engine results pages (SERPs). One aspect of SEO that often gets overlooked but is equally important is the way you name your files. It may seem insignificant
4 min read
Image Naming Conventions | Tips and Importance for SEO
Image Naming Conventions for SEO refers to the way we name pictures on websites to help them show up in search engines. By naming images with clear, specific words that describe what's in the picture, we improve the chances of people finding them online. This involves naming files clearly and concisely rather than ambiguously, such as "IMG_001.jpg,
10 min read
Python - Conventions and PEP8
Convention means a certain way in which things are done within a community to ensure order. Similarly, Coding conventions are also a set of guidelines, but for a programming language that recommends programming style, practices, and methods. This includes rules for naming conventions, indentations, comments, statements, programming practices, etc.
4 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
three90RightbarBannerImg