Understanding Python Naming Conventions, Underscores vs. Dashes


When diving into the world of Python programming, one of the first things you’ll notice is the importance of naming conventions. As in every language, there’s a standard way to name your variables, functions, and classes that helps keep your code consistent and understandable. In Python, the choice between using underscores and dashes isn’t just a matter of preference—it’s a syntax rule you need to follow.

Variables and Functions: The Snake on the Ground

In Python, variables and function names follow a convention known as snake_case. Each word in the identifier is in lowercase, and words are separated by underscores _. This convention keeps variable names readable and avoids confusion with Python’s syntax. For instance:

my_variable = 10
def my_function():
pass

Trying to use a dash (-) in these names would lead to a syntax error because Python interprets the dash as a minus sign, disrupting the flow and meaning of your code. Hence, a “no-go” in Python land.

Classes: The Humps of the Camel

When it comes to naming classes, Python developers use CamelCase (also known as CapWords). This means the first letter of each word is capitalized, and there are no underscores between words. This style makes class names stand out and signals to the reader that they are looking at a class definition. Here’s an example:

class MyClassName:
pass

class UserProfile:
def __init__(self, username):
self.username = username

The clear distinction in naming conventions for classes, compared to variables and functions, makes Python code more readable and easy to understand.

Consistency is Key

The Python Enhancement Proposal (PEP) 8 serves as the style guide for Python code and outlines these naming conventions. Staying consistent with PEP 8 not only improves readability but also aligns your code with the expectations of other Python developers, simplifying code sharing and collaboration.

In summary, when programming in Python:

  • Use snake_case for variables and functions: my_variable, calculate_age.
  • Use CamelCase for classes: DatabaseConnection, JsonResponse.

Remember, dashes have no place in Python identifiers and are reserved for arithmetic operations. By following the Python norms, you ensure your code is accessible, maintainable, and ready to blend seamlessly into the vast world of Python modules and projects.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC