Intermediate   Chapter 175 · 30 min read · Module 13: Python Testing and Debugging

Code Quality and Best Practices

Learning objectives
  • After this chapter you can follow the main PEP 8 naming and layout rules.
  • You can write clear docstrings and meaningful comments.
  • You can turn repeated code into small functions that do one job.
  • You can add type hints to function signatures.
  • You can avoid common pitfalls such as mutable default arguments and magic numbers.

Code is read far more often than it is written. You may write a function in ten minutes, but you, or a teammate, may read it many times over the next years. Code quality means making that reading easy. Clean code has clear names, a tidy layout, small functions and helpful documentation.

Python has a style guide called PEP 8 that most developers follow. It does not change what your program does. It changes how pleasant the program is to read. When everyone uses the same style, any project looks familiar and bugs are easier to see.

In this chapter you will learn the most useful habits, with before and after examples. These habits are simple, but together they make a big difference. Tools such as flake8, ruff, black and mypy can check many of them for you automatically.

Why quality matters

Low-quality code works today and hurts tomorrow. A confusing name makes a reader guess. A long function hides bugs. Copied code means that one bug must be fixed in many places. Good quality saves time, reduces mistakes and makes teamwork easier.

PEP 8: the official style guide for Python code, covering names, indentation, line length and spacing

Naming rules from PEP 8

ItemStyleExample
Variable, functionsnake_casetotal_price
ClassCapWordsShoppingCart
ConstantUPPER_CASEMAX_RETRIES
Moduleshort lowercaseutils
Private by conventionleading underscore_cache

Choose names that say what a thing is or does. A name like d forces the reader to look up its meaning, while days_left explains itself. Avoid names such as l, O and I, which look like numbers. Also avoid names that shadow built-ins, such as list, sum or max.

Example 1: Poor names and better names
# hard to read
def f(a, b):
    return a * b / 100

# easier to read
def percent_of(amount, percent):
    return amount * percent / 100

print(f(200, 15))
print(percent_of(200, 15))
30.0 30.0

Layout and style

  • Use 4 spaces for each indentation level, never mix tabs and spaces.
  • Keep lines at 79 characters or a little more; many teams allow 88 or 100.
  • Put two blank lines between top-level functions and classes, and one blank line between methods.
  • Put spaces around operators and after commas: x = a + b, not x=a+b.
  • Put imports at the top of the file, one per line, standard library first.

Docstrings and comments

A docstring is a string placed as the first statement in a function, class or module. It explains what the code does and is available at run time through help() and the __doc__ attribute. Comments explain why something is done, not what the code already says. A comment such as # add 1 to i next to i += 1 is noise, while # the API counts pages from 1 is useful.

Example 2: A docstring you can read at run time
def area_of_circle(radius):
    """Return the area of a circle with the given radius."""
    return 3.14159 * radius ** 2

print(area_of_circle.__doc__)
print(area_of_circle(2))
Return the area of a circle with the given radius. 12.56636

Small functions and the DRY idea

DRY means Don't Repeat Yourself. If you copy and paste the same lines, move them into a function. A good function does one job and has a name that describes it. If you need the word "and" to describe the function, it may be better as two functions. Small functions are easier to test and reuse.

Example 3: Removing repeated code
# repeated
price1 = 100 + 100 * 18 / 100
price2 = 250 + 250 * 18 / 100
print(price1, price2)

# with a function
TAX_PERCENT = 18

def with_tax(amount):
    return amount + amount * TAX_PERCENT / 100

print(with_tax(100), with_tax(250))
118.0 295.0 118.0 295.0

Avoid magic numbers

A magic number is a raw value in the code with no explanation, such as 0.18. Give it a name in upper case, like TAX_RATE, at the top of the file. Then the meaning is clear, and changing it needs only one edit.

Type hints

Type hints state the expected types of parameters and return values. Python does not enforce them while running, but editors and tools such as mypy use them to find mistakes, and they act as documentation. Since Python 3.10 you can write unions as int | None, and since 3.9 you can write list[int].

Example 4: Type hints
def total(prices: list[float], tax: float = 0.0) -> float:
    """Return the sum of prices plus tax."""
    return sum(prices) + tax

def find_name(names: list[str], prefix: str) -> str | None:
    for name in names:
        if name.startswith(prefix):
            return name
    return None

print(total([10.5, 4.5], 1.0))
print(find_name(["Asha", "Ravi"], "R"))
print(find_name(["Asha", "Ravi"], "Z"))
16.0 Ravi None

The mutable default argument trap

Default values are created once, when the function is defined, not each time it is called. If the default is a list or dictionary, every call shares the same object and the data piles up. The safe pattern is to use None as the default and create the list inside the function.

Example 5: Mutable default argument
def bad_add(item, items=[]):
    items.append(item)
    return items

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

print(bad_add(1))
print(bad_add(2))
print(good_add(1))
print(good_add(2))
[1] [1, 2] [1] [2]

Pythonic habits

Python has idioms that make code shorter and clearer. Loop directly over items instead of using an index, use enumerate when you need the position, use with to open files, prefer f-strings for formatting, and compare to None with is.

Example 6: Direct looping and enumerate
fruits = ["apple", "mango", "pear"]

# less clear
for i in range(len(fruits)):
    print(i, fruits[i])

# clearer
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
0 apple 1 mango 2 pear 0: apple 1: mango 2: pear
Do not chase perfection. The goal is readable code. Use a formatter such as black to settle layout arguments, and a linter such as ruff or flake8 to catch mistakes.

Python syntax

Syntax
def function_name(param: type = default) -> return_type:
    """Short summary of what the function does."""
    ...
Syntax
MAX_ITEMS = 100   # constant in UPPER_CASE
Syntax
class ClassName:   # CapWords for classes

Real-world applications

  • Team projects where many people read and edit the same code.
  • Open source libraries that need clear documentation.
  • Code reviews, where reviewers check style and clarity.
  • Long-lived business software that must be maintained for years.
  • Automatic checks in CI using linters and type checkers.

Common mistakes

Mistake: Using one-letter or vague names such as a, b, data2.
Fix: Choose names that describe the meaning, like unit_price or student_count.
Mistake: Using a list or dict as a default argument.
Fix: Use None as the default and create the object inside the function.
Mistake: Copying the same code in several places.
Fix: Move it into a function and call it, following the DRY idea.
Mistake: Leaving raw numbers such as 0.18 in the middle of a formula.
Fix: Give them an UPPER_CASE constant with a clear name.
Mistake: Writing comments that repeat the code.
Fix: Comment on why, and let the names explain what.
Mistake: Shadowing built-in names like list or sum.
Fix: Pick different names, such as items or total.

Important tips

  • Read your code again after a break and fix anything that confuses you.
  • Run a formatter and a linter before every commit.
  • Keep functions short enough to see on one screen.
  • Write the docstring first to decide what the function should do.

Key points summary

  • PEP 8: snake_case for functions and variables, CapWords for classes, UPPER_CASE for constants.
  • Docstrings document code; comments explain why.
  • DRY: do not repeat code, use functions.
  • Name constants instead of using magic numbers.
  • Type hints document types and help tools find bugs.
  • Never use a mutable object as a default argument.

Exam and interview points

  • Default argument values are evaluated once, at definition time.
  • snake_case, CapWords and UPPER_CASE conventions.
  • A docstring is available through __doc__ and help().
  • int | None union syntax needs Python 3.10 or newer.
  • Use is None, not == None.

Quick revision

  • PEP 8 = shared style
  • Names show meaning
  • Docstring = what, comment = why
  • DRY with functions
  • No mutable defaults
  • Constants not magic numbers

Frequently asked questions

Is PEP 8 a rule I must obey?

It is a guideline, not a law. Python runs code that breaks it. But most teams follow it, so following it helps others read your code.

Do type hints make Python slower or stricter?

No. Python ignores them at run time. They are for people and for tools like mypy.

How long should a function be?

There is no fixed limit, but if it does not fit on a screen or does more than one job, consider splitting it.

What tools check code quality?

flake8 and ruff check style and simple bugs, black formats code, and mypy checks type hints.

When should I write a comment?

When the reason for something is not obvious from the code, such as a workaround or a business rule.

Practise this chapter

19 practice questions Take the chapter quiz

Related chapters