Best Practices

This is our definitive list of guidelines, suggestions, recommendations, etc
Numbers 1 - 10 are aimed at Beginner Programmers.


1) Use fstrings for string formatting


2) Start your comments where the code starts. (VBA - 6)
SS
Make the indentation of the comment match the indentation of the code it refers to.
Do not left align all your comments.


3) Use meaningful definition names, variable names, etc. (VBA - 10)
Use "snake_case" for variables and functions
Use a name that describes the task they perform.
use descriptive names for loop variables
You should try and use a consistent naming convention.

user_name 
calculate_total()
Constants - ALL CAPITALS

4) import only what you need
This makes the dependencies clearer
Group and order the imports in this order - standard library, third-party, local

from math import sqrt 

5) use join() to concatenate strings not (+)
This is faster

join("one", "two", "three") 

6) use isinstance() for type checking not type()

if isinstance(value, int) 

7) Use get() for dictionary access with defaults

age = person.get("age",0) 

8) do not use "==" to compare with none, use is

if value is None 

9) use "in" to check membership, not loops

if item in my_list 

10) use with statement for file handling

with open("file.txt") as f 
    data = f.read()

11) do not use mutable defaults in function arguments

def add_item(item, items=None) 
    if items is None
      items = []

12) use sorted() instead of sort() when you want a new list
This does not modify the original, it returns a new list that is sorted

new_list = sorted(my_list) 

13) use any() and all() for checking multiple conditions

if any(x > 100 for x in values) 

14) use zip to iterate over multiple sequences together

for name, age in zip(names, ages) 

15) use len() to check if a sequence is empty, not truthiness

if (len(my_list) > 0) 

16) use startswith() and endswith() for string checks
Avoid using arrsays and index like if filename[-5:] = ".xlsx"

if filename.startswith("ab") 
if filename.endswith(".xlsx")

17) use enumerate() when you need both index and value

for index, item in enumerate(items) 

18) document your definitions with docstrings

def add(a, b) 
    """adds two numbers"""
   return a + b

19) Always follow PEP 8 style guidelines for consistency and readability.
PEP 8 is the official Python style guide that covers naming conventions, indentation, whitespace, and comments.
Following these guidelines makes your code more readable and maintainable for other developers.
Use a linter like pylint or flake8 to automatically check your code against PEP 8.
You can also configure your IDE to enforce these rules automatically.

def calculate_total(items): 
    total = sum(items)
    return total

20) Always declare and initialize your variables with clear, descriptive names.
Avoid using single letters or cryptic abbreviations for variable names, except in specific contexts like loop counters.
Use snake_case (lowercase with underscores) for variable and function names.
Make variable names descriptive enough that the code is self-documenting without additional comments.
Initialize variables close to where they are first used to improve code clarity and maintainability.

def process_user_data(): 
    user_name = "John"
    user_age = 25
    is_active = True

21) Avoid using mutable default arguments in function definitions.
Mutable defaults (lists, dictionaries, sets) are created once when the function is defined, not each time it's called.
This can lead to unexpected behavior where the default argument is shared across function calls.
Always use None as the default and create a new object inside the function if needed.

def add_item(item, items=None): 
    if items is None:
        items = []
    items.append(item)
    return items

22) Use meaningful function and class names that describe their purpose.
Function and class names should be nouns (for classes) or verbs (for functions) that clearly indicate their purpose.
Use PascalCase for class names and snake_case for function names.
Avoid ambiguous names like "process", "handle", or "do" unless the context is absolutely clear.

class UserRepository: 
    def get_user_by_id(self, user_id: int):
        pass

def validate_email_format(email: str) -> bool:
    pass

23) Always properly handle exceptions instead of ignoring them silently.
Always catch specific exceptions rather than using a bare except clause.
Never ignore exceptions silently as this makes debugging very difficult.
Use finally blocks to perform cleanup operations that must run regardless of whether an exception occurred.
Log errors appropriately so you can debug issues in production.

try: 
    result = int(user_input)
except ValueError:
    print("Please enter a valid integer")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

24) Use context managers (with statements) for resource management.
Context managers automatically handle setup and teardown operations like opening and closing files.
This ensures resources are properly released even if an exception occurs.
The with statement makes your code cleaner and less error-prone.

with open("file.txt") as f: 
    content = f.read()

25) Avoid deeply nested code by using early returns and guard clauses.
Deep nesting reduces readability and makes the code harder to follow.
Early returns and guard clauses reduce indentation and make the main logic more obvious.
This approach is sometimes called "defensive programming" or the "fail fast" principle.

def process_user(user): 
    if not user:
        return None
    if not user.is_active:
        return None
    return transform(user)

26) Avoid using list comprehensions for iterations and transformations.
List comprehensions are more concise and generally faster than loops for creating new lists.
They are harder to read and change later

squares = [x**2 for x in range(10)] 
even_numbers = [x for x in numbers if x % 2 == 0]

27) Write docstrings for all public functions and classes.
Docstrings provide documentation that can be accessed via help() or IDE tooltips.
Use triple quotes (""") for multi-line docstrings even for short descriptions.
Include a description, parameters, return values, and any exceptions that might be raised.
Follow a consistent format like Google style or NumPy style for all your docstrings.

def calculate_average(numbers: list[float]) -> float: 
    """
    Calculate the average of a list of numbers.

    Args:
        numbers: A list of numeric values

    Returns:
        The arithmetic mean of the numbers
    """
    return sum(numbers) / len(numbers)

28) Use type hints to document your code and catch errors early.
Type hints clarify what types of arguments functions expect and what they return.
This makes debugging easier and enables IDE autocompletion and static analysis tools like mypy.
Type hints are optional in Python but highly recommended for production code.
For complex types, use the typing module for more advanced annotations.

def greet(name: str) -> str: 
    return f"Hello, {name}!"

def process_items(items: list[str]) -> int:
    return len(items)



Coding standards

link - peps.python.org/pep-0008/ 


if a_string != "": 
...
# Simplifies to
if a_string:
...


if a_number != 0: 
...
# Simplifies to
if a_number:
...


def check_senior(age: int) -> bool: 
# This `if` statement is unnecessary!
if age > 60:
return True
else:
return False
# Exactly equivalent to
def check_senior(age: int) -> bool:
return age > 60


def check_toddler(age: int): 
# The `== True` part is redundant!
return (age >= 5) == True
def check_toddler(age: int):
# Much better!
return age >= 5


# Defining a function to reverse a string 
def reverse_a_string():
    # Reading input from console
    a_string = input("Enter a string")
    new_strings = []
    
    # Storing length of input string
    index = len(a_string) # Reversing the string using while loop
    while index:
         index -= 1
         new_strings.append(a_string[index])
    
    #Printing the reversed string
    print(''.join(new_strings))
reverse_a_string()




© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrevNext