Python
camel case
underscores
coding style
programming conventions

Should I use camel case or underscores in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

When working on a Python project, one often encounters decisions about naming conventions. One such dilemma is choosing between "camel case" and "underscores" for naming variables, functions, and other identifiers. This article explores these two popular conventions, helping you make an informed choice based on Python's best practices and your project requirements.

Understanding Camel Case and Underscores

Camel Case: In camel case convention, words are concatenated without spaces, and each word within the identifier starts with an uppercase letter, except the first word. For example: `camelCaseExample`.

Underscores: Underscore naming uses the underscore character (`_`) to separate words. All words are usually in lowercase. For instance: `underscore_example`.

Python Naming Conventions

Python's official style guide, known as PEP 8, provides recommendations that are widely adopted by Python developers:

  • Variables and Functions: Use `snake_case`. The PEP 8 guide specifies that function and variable names should be all lowercase, with words separated by underscores.
  • Constants: Use `UPPER_CASE`. Constants are typically written with all uppercase letters with words separated by underscores.
  • Class Names: Use `CamelCase`. This is an exception to the underscore rule, where class names should capitalize each word and not include underscores.

Examples

Let's review some examples to illustrate these conventions:

  • Variable:
  • Function:
  • Constant:
  • Class:
  • Readability and Maintenance: Code that follows PEP 8 rules is typically easier to read and maintain. This consistency is invaluable when working in teams or on open-source projects.
  • Community Acceptance: Using standard conventions makes it easier for others in the Python community to understand your code.
  • Tool Support: Many Python tools and linters automatically check for PEP 8 compliance, smoothing out the development and review processes.
  • Legacy Code: In projects with substantial existing code that doesn't adhere to PEP 8, enforcing the style guide may incur unnecessary refactoring costs.
  • Library Integration: Sometimes the integration with third-party libraries or APIs will require the use of non-standard conventions that favor camel case.

Course illustration
Course illustration

All Rights Reserved.