Thuta Learning
Python
IntermediateProgrammingBeginner

Best Practices

PythonLesson 2925 min

What you'll walk away with

  • Name variables, functions, classes and constants the PEP 8 way
  • Explain the mutable default argument bug and fix it with a None default
  • Refactor a function into a clear shape with type hints, a docstring and a ValueError
  • Tell apart the jobs of a formatter, a linter, a type checker and a test runner

Explain it simply

Explain it simply

You write code more for people than for the computer. Python will happily run a function called proc with variables named x and d. But you next month, or a teammate tomorrow, will spend minutes working out what it does.

Best practices are the conventions the Python community has agreed on: how to name things, how to indent (four spaces), giving each function one job, and avoiding traps that cause bugs. When everyone follows the same rules, any Python project you open feels familiar.

Problem → Why → Solution

The problem: code that runs but cannot be trusted

The proc() function below is right the first time you call it. The second time, it should return 20% of a single 1000, which is 200.0, but it returns about 5566.67 instead. The names tell you nothing about what is being calculated, and the bare except: turns every possible error into a silent 0.

messy.py
def proc(d, l=[]):
    for x in d:
        if x != None and x > 0: l.append(x * 0.2)
    try:
        return sum(l) / len(l)
    except:
        return 0

print(proc([50000, None, 32500]))   # 8250.0
print(proc([1000]))                 # 5566.666..., not 200.0: old values remain

Why does this happen?

The default l=[] is created once, when the function is defined, not on every call. So the values from the first call are still in the list. Unclear names, a bare except and a crammed one-line if all help hide that bug, which is why it is so hard to spot.

Core concept: readability is a feature

Python's style guide is PEP 8. It recommends four spaces per indentation level and lines of at most 79 characters (many teams agree on a slightly longer limit enforced by a formatter). The most important part is naming, because the shape of a name tells you what kind of thing it is.

KindStyleExample
Variable, functionsnake_casetotal_price, calculate_tax()
ClassPascalCaseEmployee, OrderItem
ConstantUPPER_SNAKE_CASETAX_RATE, MAX_RETRIES
Internal by convention_leading_underscore_cache, _parse_row()

A function should do one job, and its name should say what that job is. If calculate_tax() only calculates tax and leaves printing or file writing to its caller, it is easy to test and reusable anywhere. Type hints such as (income: float) -> float say what goes in and what comes out, and the docstring explains why the function exists. Python does not check type hints at runtime; type checkers such as mypy and your editor use them.

Handle errors explicitly too. When data is wrong, raise an exception such as ValueError with a message instead of quietly returning 0 or None. Compare with None using is rather than ==, because there is exactly one None object and a class can override ==. Never use a mutable object such as a list or dict as a default value; default to None and create a fresh one inside the function.

Comments and docstrings have different jobs. A docstring describes what a function does for anyone calling it, and tools such as help() display it. A comment explains why one particular line is written the way it is, for example why tax is rounded to cents. A comment that only repeats the code, such as # add 1 to x, is noise that goes stale the moment someone edits the line.

Mental model: the six-month test
  1. Does each name say what it is?
  2. Does each function do one job?
  3. Do hints and docstring state the deal?
  4. Do failures raise, loudly?

Write for the version of you who reopens this file in six months.

General pattern

python
CONSTANT_NAME = value


def function_name(param: Type, option: Type | None = None) -> ReturnType:
    """One line saying what the function returns or does."""
    if option is None:
        option = make_fresh_default()
    if not is_valid(param):
        raise ValueError("clear message about what is wrong")
    return result

Constants use UPPER_SNAKE_CASE and functions use snake_case. Parameters and the return value carry type hints, and the docstring is the first statement. A default that needs to be mutable starts as None, is checked with is None, and is created fresh. Bad input raises an exception.

Example: tax code written the clean way

This example fixes the problems from the messy version one by one. A dataclass gives the employee data a clear shape, calculate_tax() raises ValueError for bad input, and add_tag() avoids the mutable default trap with a None default.

clean_tax.py
from dataclasses import dataclass

TAX_RATE = 0.2  # module-level constant: UPPER_SNAKE_CASE


@dataclass
class Employee:  # classes use PascalCase
    name: str
    income: float


def calculate_tax(income: float, tax_rate: float = TAX_RATE) -> float:
    """Return the tax owed on a yearly income, rounded to cents."""
    if income < 0:
        raise ValueError("income cannot be negative")
    return round(income * tax_rate, 2)


def add_tag(tag: str, tags: list[str] | None = None) -> list[str]:
    """Add a tag to the caller's list, or to a brand-new list."""
    if tags is None:  # compare with None using 'is'
        tags = []
    tags.append(tag)
    return tags


staff = [Employee("Aye", 50_000), Employee("Ko Ko", 32_500.5)]
taxes = [calculate_tax(person.income) for person in staff]
print(f"Taxes: {taxes}")
print(add_tag("new"), add_tag("vip"))

try:
    calculate_tax(-1)
except ValueError as err:
    print(f"Rejected: {err}")

Code breakdown

  1. Line 3TAX_RATE = 0.2 # module-level constant: UPPER_SNAKE_CASE

    Instead of a bare 0.2 scattered through the code, the rate lives in one named constant. When the rate changes, you edit one line.

  2. Lines 6-9class Employee: # classes use PascalCase

    @dataclass writes __init__ and __repr__ for you. Compared with dict keys like person["income"], an attribute such as person.income lets the editor flag a typo immediately.

  3. Lines 14-15raise ValueError("income cannot be negative")

    A negative income means the data is wrong. Returning 0 would slip a false number into a report, so the function complains loudly with an exception.

  4. Lines 21-22if tags is None: # compare with None using 'is'

    With tags=None as the default and a new list made on each call, add_tag("new") and add_tag("vip") get separate lists. The output ['new'] ['vip'] proves it.

  5. Line 28taxes = [calculate_tax(person.income) for person in staff]

    The list comprehension says "the tax for every employee" in one line. round() turns 32500.5 × 0.2 into a clean 6500.1.

You should see
Taxes: [10000.0, 6500.1]
['new'] ['vip']
Rejected: income cannot be negative

See the mutable default trap for yourself

Default values are stored on the function object in __defaults__. Run the code below and you can watch two calls share one list. Immutable defaults such as a tuple, str, int or None are safe because they cannot be changed in place.

defaults_trap.py
def remember(item, seen=[]):
    seen.append(item)
    return seen

print(remember("a"))           # ['a']
print(remember("b"))           # ['a', 'b']  <- the same list again
print(remember.__defaults__)   # (['a', 'b'],)

Let tools enforce the rules

Checking style rules by hand in code review wastes time and starts arguments. Run tools on every save in your editor, or in CI, and reviews can focus on the logic.

ToolJob
Black or ruff formatRewrites layout automatically (formatter)
RuffFinds problems like unused imports and bare excepts (linter)
mypyFinds calls that break the type hints (type checker)
pytestRuns tests that prove functions behave correctly

In real projects

Where this shows up in real projects

In team projects these rules are written into pyproject.toml, and a pre-commit hook plus the CI pipeline run the formatter, linter, type checker and tests on every commit. If anything fails, the pull request cannot be merged. Arguments like "tabs or spaces?" disappear, and reviewers spend their attention on business logic.

When you refactor a long script, follow the shape of this lesson: split configuration (constants), input reading, the calculation logic and output writing into separate functions. Because the logic functions no longer touch files or the network, pytest can test them with plain inputs and outputs. Validate input once, where it enters the system, and the inner functions can trust the data they receive.

Common mistakes

Common mistakes

1. Using a list or dict as a default argument

def add(item, items=[]) shares one list across every call, so values leak from one call into the next. Default to items=None and create a new list with if items is None: items = []. Linters such as Ruff can flag this pattern.

2. Catching everything with a bare except:

except: catches every exception, including KeyboardInterrupt from Ctrl+C, and hides bugs you never anticipated. Name the type you can actually handle, such as except ZeroDivisionError:.

3. Merging unrelated rules in the name of DRY

Two similar-looking pieces of code do not always belong in one function. A tax rule and a shipping rule may match today and change separately next month. Two clear functions beat one "generic" function that keeps growing flag parameters.

Best practices

Best practices

  • Give every project its own virtual environment and record its dependency versions in a file.
  • Before making code faster, measure where it is actually slow with cProfile instead of guessing.
  • Pass data in as parameters and return results instead of modifying global variables.
  • Open files in a with block so they are closed even when an error occurs.

Mini challenge

Mini challenge: refactor an order script

Write code that reads "name, amount" lines and totals the amount per customer, following this lesson's rules. Lines with a negative amount are skipped with the reason printed.

  • An Order dataclass with customer and amount fields
  • parse_order(line) -> Order raises ValueError for a negative amount
  • total_by_customer(orders) -> dict[str, float] uses no mutable default argument
  • Every function has type hints and a docstring
orders.py
from dataclasses import dataclass


@dataclass
class Order:
    # TODO: a customer (str) field and an amount (float) field
    ...


def parse_order(line: str) -> Order:
    # TODO: docstring
    # TODO: split on the comma, strip the spaces, convert the amount with float()
    # TODO: raise ValueError for a negative amount
    ...


def total_by_customer(orders: list[Order]) -> dict[str, float]:
    # TODO: docstring, then sum the amounts per customer into a new dict
    ...


lines = ["Aye, 12.5", "Ko Ko, 8", "Aye, 7.5", "Mya, -3"]
# TODO: parse each line, print "Skipped: <reason>" for bad ones, then print the totals

Expected: The program prints: Skipped: negative amount for Mya {'Aye': 20.0, 'Ko Ko': 8.0}

Show hint

Split with name, raw_amount = line.split(","). Add into the dict with totals.get(name, 0.0) + amount. Call parse_order() inside try/except ValueError.

Show solution
orders.py
from dataclasses import dataclass


@dataclass
class Order:
    customer: str
    amount: float


def parse_order(line: str) -> Order:
    """Turn a 'name, amount' line into an Order, rejecting negative amounts."""
    name, raw_amount = line.split(",")
    amount = float(raw_amount)
    if amount < 0:
        raise ValueError(f"negative amount for {name.strip()}")
    return Order(name.strip(), amount)


def total_by_customer(orders: list[Order]) -> dict[str, float]:
    """Return the summed order amount for each customer."""
    totals: dict[str, float] = {}
    for order in orders:
        totals[order.customer] = totals.get(order.customer, 0.0) + order.amount
    return totals


lines = ["Aye, 12.5", "Ko Ko, 8", "Aye, 7.5", "Mya, -3"]
orders: list[Order] = []
for line in lines:
    try:
        orders.append(parse_order(line))
    except ValueError as err:
        print(f"Skipped: {err}")
print(total_by_customer(orders))

Quick quiz 1 / 3

Given def add(x, bucket=[]): bucket.append(x); return bucket, what does the second call return after add(1) then add(2)?

Quick quiz 2 / 3

Which set of names follows PEP 8?

Quick quiz 3 / 3

What happens when you call area("3") on def area(width: float) -> float: return width * width?

What to remember

  • PEP 8: four-space indents, snake_case functions and variables, PascalCase classes, UPPER_SNAKE_CASE constants.
  • Give each function one job and state its contract with type hints and a docstring.
  • Never use a mutable default argument: default to None and check with is None.
  • Raise exceptions for bad data, and let a formatter, linter, type checker and tests run automatically.

The Python Tutorial — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Best Practices | Thuta Learning