Python Coding Standards and Conventions
Introduction
Coding standards and conventions are a critical aspect of coding in any programming language, including Python. They provide guidelines that shape a coder’s style of writing code, leading to more readable, maintainable, and efficient programs.

In Python, these rules are defined in PEP8, an official style guide for Python code. This guide helps both beginners and experienced coders to write code that is cleaner and more efficient. Remember, the goal is to make your code as readable as human language. In this article, we’ll look at Python coding standards and conventions covering aspects like indentation, naming conventions, import statements, and more.
Why should you follow Python coding standards and conventions?
These rules enhance the readability and consistency of your code. Consistent coding standards can make it easier for you to debug your code, as well as make it easier for others to understand and contribute to your code.
Moreover, adopting best practices right from the start will make you a better programmer in the long run. It’s always much better to prevent mistakes from happening rather than fixing them.
Let’s dive in and understand these principles in detail.
Coding style
Indentation
In Python, indentation is not just for readability, it’s a language requirement. Python uses indentation to indicate blocks of code. PEP8 standard suggests using 4 spaces for each indentation level. Using spaces instead of tabs is preferred as it ensures consistency across different IDEs and text editors.
# Good
def function():
for i in range(5):
print(i)
# Bad
def function():
for i in range(5):
print(i)
Line Length
According to PEP8, no line should be longer than 79 characters . If a script or comment line is longer than this value, it should be broken into smaller lines.
# Good
print("This is a very long line that is split into two lines for readability. It's a good practice to follow.")
# Bad
print("This is a very long line that is not split into smaller lines making it harder to read within the 79 character limit.")
Line Breaks
Always break lines before binary operators to improve readability.
# Good
total = (first_variable
+ second_variable
- third_variable)
# Bad
total = (first_variable +
second_variable -
third_variable)
Naming Conventions
Naming conventions in Python are a set of rules to help you choose names of variables, functions, classes, modules, and other Python components.
-
Variables: Variables in Python should be named using
snake_case
which means all lowercase letters with underscores between words.“`python
Good
my_variable = 10
Bad
MyVariable = 10 myVariable = 10 my-variable = 10 “`
-
Functions: The function names in Python should also be in
snake_case
.“`python
Good
def my_function(): pass
Bad
def myfunction(): pass def MyFunction(): pass “`
-
Classes: The class names in Python should be in
CamelCase
, meaning all words are concatenated without spaces, and each word starts with a capital letter.“`python
Good
class MyClass: pass
Bad
class my_class: pass class myclass: pass “`
-
Constants: Constants are usually declared and assigned on a module level and written in all capital letters with underscores separating words.
“`python
Good
MAX_SIZE = 100
Bad
max_size = 100 “`
File and Directory Names
The file and directory names should be in snake_case
. It is advisable to go for all lowercase letters to avoid confusion with class names.
# Good
my_script.py
# Bad
myScript.py
My_Script.py
Import Statements
In Python, import statements are used to include functions, classes and variables from another Python file. Import statements should always be at the top of the file, after module docstrings, and followed by constants and global variable definitions.
Additionally, imports should be grouped in the following order:
- Standard library imports
- Related third party imports
- Local application/library specific imports
# Good
import os # Standard library import
import flask_jwt # Third party import
from my_app import main_function # Local application import
# Bad
import os
from my_app import main_function
import flask_jwt
Each group should be separated by a blank line.
Comments and Documentation Strings (Docstrings)
Understanding Python’s document string conventions is equally important. Comments are descriptions that help programmers better understand the intent and functionality of the program.
In Python, comments begin with a #
symbol. PEP 257 describes good docstring conventions.
# This is a single line comment
"""
This is an example of
a multi-line comment
"""
def my_function():
"""
This is a docstring for my_function.
It describes what the function does.
"""
pass
Handling Exceptions
Never use a bare except:
clause in your Python programs. Always try to catch specific errors you expect might happen during your program’s execution. Using a bare except:
clause will catch all exceptions, including keyboard interrupts and system exits you might need when forcing a program to quit.
# Good
try:
x = 1 / 0
except ZeroDivisionError:
print('You tried to divide by zero!')
# Bad
try:
x = 1 / 0
except:
print('An error happened!')
White Spaces in Expressions and Statements
In Python, white spaces increase readability of your code. However, excessive white space can be just as confusing as not enough. Avoid redundant white space in the following situations:
- Immediately after a parenthesis, bracket or a brace.
- Immediately before a comma, a semicolon, or a colon.
- Immediately before the open parenthesis that starts the argument list of a function call.
# Good
spam(ham[1], {eggs: 2})
x, y = y, x
# Bad
spam( ham[ 1 ], { eggs : 2 } )
x , y = y , x
Coding Practices
- Always use
is
oris not
while comparing withNone
. For instance,if x is None
orif x is not None
. - Use list comprehensions, set comprehensions, and dictionary comprehensions for simple creation of data structures whenever possible.
- Use
return
statement wisely. Do not addreturn None
at the end of the function. It is implicit. Same wise do not useelse
afterif
andreturn
. It is also implicit.
# Good
def my_function(b):
if b == 1:
return True
# Bad
def my_function(b):
if b == 1:
return True
else:
return None
Conclusion
Adhering to Python’s coding standards and conventions may seem like a lot of extra work, but remember, the primary reasons for following these guidelines are to facilitate code readability and maintainability which are hallmarks of good coding. The best way to learn these conventions is to read through Python’s PEP 8 and PEP 257, and apply these standards in your day-to-day coding. Always remember that “Code is read much more often than it is written”, that’s why it makes more sense to optimize for readability and clarity rather than writing complex and shorter code.
Happy Python coding!