Skip to content

1.1 Naming Conventions

Bora Canbula edited this page Dec 2, 2023 · 1 revision

Python does not have strict rules, however we should follow some naming conventions to improve the quality and readability of our code. All the conventions, which are mentioned in this page, are taken from PEP8: Style Guide for Python Code.

Conventions about Names

  • Names to Avoid: Never use the characters l (lowercase letter el), O (uppercase letter oh), or I (uppercase letter eye) as single character variable names.

  • Packages: Packages are folders including the modules. Their names should be short, all-lowercase names without underscores. Examples: numpy, matplotlib, selenium.

  • Modules: Modules are single Python files, which can include some classes or functions and to be imported to some other Python files or run directly. Their names should be short, all-lowercase names, can have underscores. Examples: random, memory_profiler.

  • Classes: Class names should follow the CapWords (upper camel case) convention. Examples: MyClass, RandomNumberGenerator, CustomSchedule.

  • Functions: Function names should follow the snake_case convention. Example: generate_coordinates, calculate_result.

  • Variables: Variable names should follow the snake_case convention. Example: final_value, x_mean, thread_counter.

  • Constants: Constant names should follow the ALL_UPPERCASE convention. Example: PI, NUMBER_OF_THREADS, SIZE_LIMIT.

Underscore Usage

In Python, we don't have public, private, and protected keywords, however we can use leading underscores to have some kind of encapsulation. On the other hand, keep in mind that one can still access to these kind of variables by using name mangling.

  • _single_leading_underscore: Weak "internal use" indicator. from M import * does not import objects whose names start with an underscore.

  • single_trailing_underscore_: Used by convention to avoid conflict with keyword.

  • __double_leading_underscore: When naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo).

  • __double_leading_and_trailing_underscore__: "Magic" objects or attributes that live in user-controlled namespaces (__init__, __import__ etc.). Never invent such names, only use them as documented.

Example codes can be found in Week02 folder.