Python Coding Standards

Ram Tamang
5 min readAug 8, 2023

--

Programming Guidelines

Based on community and users python has set a coding standards and best practices known as a “PEP 8 (Python Enhancement Proposal 8). PEP 8 provides guidelines for writing clean, readable, and maintainable Python code. These standards provide a comprehensive set of guidelines for writing clean, readable, and maintainable Python code. Adhering to these standards promotes consistency across projects and enhances collaboration among developers. By following these best practices, you contribute to the creation of high-quality software that is easier to understand, maintain, and extend. Following these standards helps ensure consistency across projects and make code more understandable for others and for future. Here are some key points from PEP 8.

1. Indentation

  • Use 4 spaces per indentation level.
  • Avoid using tabs for indentation.
# Good
def my_function():
if x > 0:
print("x is positive")

2. Line Length

  • Use max 79 character per line
  • Break long expressions over multiple line and use parentheses for readability.
# Good
long_expression = (
something + another_thing + something_else +
yet_another_thing
)

3. Imports

  • Use separate lines for imports and avoid using *.
# Good
import module_name
from module_name import function_name

4. Whitespace in Expressions and Statements:

  • Use a single space before and after operators.
# Good
result = x + y

5. Comments:

  • Use comments to explain why, not what.
# Good
# Calculate the total cost
total_cost = price * quantity # multiplying price and quantity

6. Function and Variable Names:

  • Use lowercase with underscores for function and variable names.
# Good
def calculate_total_price():
pass

7. Class Names:

  • Use CamelCase for class names.
# Good
class MyClass:
pass

8. Whitespace in Function and Class Definitions:

  • Put a single space after the colon.
# Good
def my_function(argument: int) -> str:
pass

9. String Quotes:

  • Use single quotes for string literals.
# Good
message = 'Hello, World!'

10. Docstrings:

  • Use docstrings to provide descriptions.

# Good
def add(a, b):
"""
Add two numbers and return the result.

Args:
a (int): The first number.
b (int): The second number.

Returns:
int: The sum of a and b.
"""
return a + b

11. Naming Conventions:

  • Follow PEP 8’s naming conventions.
# Good
CONSTANT_VALUE = 42

class MyClass:
def my_method(self):
pass

def my_function_name():
pass

12. Single Responsibility Principle (SRP):

  • Aim for functions/classes with a single responsibility to enhance maintainability.

# Bad - Mixing responsibilities
def process_data_and_send_email(data):
process_data(data)
send_email(data)

# Good - Separating responsibilities
def process_data(data):
# Process data logic here

def send_email(data):
# Send email logic here

13. Avoid Global Variables:

  • Minimize global variables to prevent unexpected side effects.

# Bad - Using a global variable
total = 0

def add_to_total(value):
global total
total += value

# Good - Using a function parameter
def add(a, b):
return a + b

14. Avoid Magic Numbers and Strings:

  • Use constants for better readability and maintainability.

# Bad - Using magic number
if age >= 18 and age <= 65:
pass

# Good - Using named constants
MIN_AGE = 18
MAX_AGE = 65

if MIN_AGE <= age <= MAX_AGE:
pass

15. Use Enumerations for Constants:

  • Improve readability by using enumerations for related constants.

# Bad - Using plain constants
MONDAY = 0
TUESDAY = 1

# Good - Using enums
from enum import Enum

class Weekday(Enum):
MONDAY = 0
TUESDAY = 1

16. Avoid Nested Loops and Deep Nesting:

  • Limit nesting for improved readability.

# Bad - Deep nesting
for i in range(10):
for j in range(10):
if condition(i, j):
do_something(i, j)

# Good - Reduced nesting
for i in range(10):
if condition(i):
for j in range(10):
if condition(j):
do_something(i, j)

17. Context Managers (with Statements):

  • Use with statements for resource management.

# Bad - Manual file handling
file = open('file.txt', 'r')
content = file.read()
file.close()

# Good - Using context manager
with open('file.txt', 'r') as file:
content = file.read()

18. String Formatting and F-Strings:

  • Use f-strings for concise string formatting.

# Bad - String concatenation
full_name = first_name + ' ' + last_name

# Good - F-strings
full_name = f'{first_name} {last_name}'

19. Duck Typing:

  • Focus on behavior, not type.

# Duck typing
def get_length(obj):
return len(obj)

my_list = [1, 2, 3]
length = get_length(my_list) # Works with any iterable

20. Avoid Bare except Statements:

  • Catch specific exceptions or use except Exception as e for better error handling.

# Bad - Bare except
try:
result = risky_operation()
except:
handle_error()

# Good - Catch specific exception
try:
result = risky_operation()
except ValueError:
handle_value_error()

# Better - Catch specific exceptions with a base class
try:
result = risky_operation()
except (ValueError, TypeError) as e:
handle_error(e)

21. Use enumerate() for Indexing:

  • Use enumerate() for cleaner indexing in loops.

# Bad - Manual indexing
for i in range(len(items)):
print(f'Item at index {i}: {items[i]}')

# Good - Using enumerate
for i, item in enumerate(items):
print(f'Item at index {i}: {item}')

Adopting a consistent coding style is a crucial step in the software development process. By adhering to these coding standards, you contribute to creating code that is not only functional but also comprehensible and maintainable. Remember that these standards are meant to guide you, not restrict you. Adapt them as needed to suit the specifics of your project, and always prioritize readability and collaboration.

This will guide on writing Python code that aligns with industry best practices. Your dedication to following these standards will lead to improved code quality and a more enjoyable development experience for you. Further more you can follow references.

References

  1. PEP 8 — Style Guide for Python Code The official Python Enhancement Proposal (PEP 8) document outlines the style guide for Python code. It covers coding conventions, naming conventions, and more.
  2. Google Python Style Guide The Google Python Style Guide provides additional recommendations for writing clean and readable Python code. It includes guidelines on indentation, comments, and more.
  3. The Zen of Python (PEP 20) PEP 20, also known as “The Zen of Python,” contains guiding principles for writing computer programs in Python. It offers insights into the design philosophy of Python.
  4. Clean Code: A Handbook of Agile Software Craftsmanship This book by Robert C. Martin provides a deep dive into writing clean and maintainable code. While not Python-specific, the principles discussed are highly applicable to Python development.

--

--