Identifier (Variables, Constants, Functions, Classes, Modules & Packages) Naming Convention in Python
- Rules for Identifier
- Conventions for identifier
- Naming Variables
- Naming Constants
- Naming Functions
- Naming Classes
- Naming Modules
- Naming Packages
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:
- Must start with _ (underscore) or alphabets (a - z or A - Z)
- Lower case & Upper case are treated different identifiers i.e.
area
&Area
are two different variables. - 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:
- _name single underscore before identifier name is for internal use or for private entities.
- __name double underscore before identifier name is used to "mangle" class attributes which is useful in inheritance chain.
- __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
- Use all lower case
- Use snake case. For Example:
account_id
,area_circle
, ... etc.
Naming Constants
- Use all upper case
- Words separated by underscore ( _ ) but all upper case. For Example:
GOLDEN_RATIO
,MIN_RATE
, ... etc.
Naming Functions
- Use all lower case
- Use snake case. For Example:
calculate_area
,say_hello
, ... etc.
Naming Classes
- Use upper camel case. (CapWords convention)
- First character upper case and joined. For Example:
Polynomial
,UserAccount
,BankAccount
, ... etc.
Naming Modules
- Use short names
- All lower case.
- Can have underscore.
- Examples:
db_shortcuts
,dbutils
, ... etc
Naming Packages
- Use short names
- All lower case.
- Preffered no underscore.
- Examples:
math
,utilities
, ... etc