Identifier (Variables, Constants, Functions, Classes, Modules & Packages) Naming Convention in Python

Table of Contents

In programming, name given to variables, constants, functions, classes, modules and packages is known as identifier. This article explains naming convention for identifier in Python.

While naming identifiers, they must follow certain rules and certain conventions. Rules must be followed otherwise they produce errors while conventions are necessary for readability and making code similar among developers.

Rules for Identifier

While naming identifiers following rules must be folowed in Python:

  1. Must start with _ (underscore) or alphabets (a - z or A - Z)
  2. Lower case & Upper case are treated different identifiers i.e. area & Area are two different variables.
  3. Reserved words (also known as Keywords) can not be used. For example: True, if, for, ... etc cannot be used as identifier.

Conventions for Identifier

Following conventions are followed while naming identifiers in Python:

  1. _name single underscore before identifier name is for internal use or for private entities.
  2. __name double underscore before identifier name is used to "mangle" class attributes which is useful in inheritance chain.
  3. __name__ double underscore before and after variable name also known as dunder is used for system defined names that have special meaning to the interpreter.
    Dont't create or invent them by yourself and use pre-defined dunder in Python.
    For examples: __init__, __repr__, ... etc.

Naming Variables

  1. Use all lower case
  2. Use snake case. For Example: account_id, area_circle, ... etc.

Naming Constants

  1. Use all upper case
  2. Words separated by underscore ( _ ) but all upper case. For Example: GOLDEN_RATIO, MIN_RATE, ... etc.

Naming Functions

  1. Use all lower case
  2. Use snake case. For Example: calculate_area, say_hello, ... etc.

Naming Classes

  1. Use upper camel case. (CapWords convention)
  2. First character upper case and joined. For Example: Polynomial, UserAccount, BankAccount, ... etc.

Naming Modules

  1. Use short names
  2. All lower case.
  3. Can have underscore.
  4. Examples: db_shortcuts, dbutils, ... etc

Naming Packages

  1. Use short names
  2. All lower case.
  3. Preffered no underscore.
  4. Examples: math, utilities, ... etc