Skip to main content

Naming Conventions in Python

🐍 The naming conventions in Python are defined in the official PEP 8 Style Guide. They ensure uniform, readable, and maintainable code. Here’s a comprehensive overview:


🧠 Naming Conventions in Python (PEP 8)
#

🔤 1. General Rules
#

  • Use descriptive names – no cryptic abbreviations.
  • Use English terms, unless you’re working on a project with another language.
  • Use snake_case for functions, variables, and methods.
  • Use PascalCase for classes.
  • Use UPPER_CASE for constants.

📦 2. Modules and Packages
#

Element Convention Example
Module name lowercase or snake_case math_tools.py
Package name lowercase utilities

🧮 3. Variables
#

Type Convention Example
Local Variable snake_case student_count
Global Variable snake_case max_value
Constant UPPER_CASE PI = 3.14159

🧪 4. Functions and Methods
#

Type Convention Example
Function snake_case calculate_grade()
Instance Method snake_case draw_shape()
Class Method snake_case create_from_dict()
Static Method snake_case is_valid()

🧱 5. Classes
#

Type Convention Example
Class PascalCase Student, TurtleArtist
Exception Class PascalCase FileError

🔮 6. Magic Methods (Dunder Methods)
#

Type Convention Example
Special Methods __method__ __init__, __str__, __repr__

🛡️ 7. Private and Protected Names
#

Type Convention Example
Protected _name _internal_method()
Private __name __secret_data

🧪 8. Class Attributes vs. Instance Attributes
#

  • Class attributes: snake_case, often with @classmethod
  • Instance attributes: self.attribute_name

🧠 Memory Rules:
#

  • Functions, Variables, Methodssnake_case
  • Classes, ExceptionsPascalCase
  • ConstantsUPPER_CASE
  • Private Things → start with _ or __

Yes, CamelCase exists in Python – but it’s only recommended in specific cases. 🐍 The official convention according to PEP 8 is:


🐫 CamelCase vs. PascalCase vs. snake_case
#

Style Description Example Usage in Python
snake_case Lowercase with underscores calculate_grade() ✅ Functions, Variables
PascalCase Capital letters at word beginnings StudentClass ✅ Class names
camelCase First word lowercase, then capitalized calculateGrade() Not recommended in Python

❌ Why camelCase is not common in Python:
#

  • It comes from other languages like JavaScript, Java, or C#.
  • Python prefers readability through underscores (snake_case).
  • Consistent style is important for collaboration and maintenance.

✅ When you still see CamelCase:
#

  • When working with external libraries that come from other languages.
  • In JSON data or APIs, e.g.:
    {
      "userName": "Lena",
      "userAge": 12
    }
    
  • When importing JavaScript objects in web projects with Python backends.

🧠 Conclusion for Students:
#

In Python:
🔤 Functions & Variablessnake_case
🧱 ClassesPascalCase
🐫 camelCase → better avoid!