Define a Python function with def name(parameters): and indent its body. Call it by adding parentheses after its name and supplying any required arguments. Use return when the caller needs a result. A function that finishes without returning a value gives its caller None.
def label_for(title, number):
return f"{number}. {title}"
label = label_for("Review", 2)
assert label == "2. Review"
title and number are parameters in the definition. The supplied values "Review" and 2 are arguments at the call. Giving inputs names makes their roles visible where the work happens.
Return values that another caller can use
print sends text to a stream. It returns None. return gives the caller a value, allowing it to decide whether to display it, write it, or pass it to another function. A program that generates a status label can compute the label independently from its presentation.
Return the label if it will appear on a report page and in a text export. Each caller can then decide where to put it. If you want a script to show the label in the terminal, the caller can use print(label).
Use keyword arguments to explain a call
Calls can supply parameters in position with label_for("Review", 2) or by matching names with label_for(title="Review", number=2). A named argument is helpful when its value alone is ambiguous. Two adjacent flags written as True, False are difficult to interpret without the definition.
A default should be a sensible result of leaving something unspecified. If the caller must choose a unit or a date format, require it or make the default part of the documented contract. To make selected arguments available only by name, place a bare * before them in the definition.
def room_label(room, *, building="West"):
return f"{building} / {room}"
assert room_label("104") == "West / 104"
assert room_label("208", building="East") == "East / 208"
Calling room_label("208", "East") raises TypeError because the second value has to be named. If an argument name is used by callers, consider it part of the public interface before changing it.
Avoid sharing mutable default arguments
Python evaluates a default when it reaches the function definition, which is often when the module loads. With def collect(item, items=[]):, every call that omits items shares the same list. Append "first" in one call and the next call starts with ["first"]. Use None as the default and make a fresh list inside the function.
def collect(item, items=None):
if items is None:
items = []
items.append(item)
return items
assert collect("first") == ["first"]
assert collect("second") == ["second"]
This version still changes an explicitly supplied list. If a caller supplies a list but wants it preserved, copy that list before appending or design the function to return a new one. State the ownership rule in the name or docstring.
Decide what an early return means
A function can return early when it detects a clearly defined boundary case. An empty list could produce an empty result. A missing required value could raise a specific exception. Avoid using None for several unrelated outcomes if callers need to tell them apart.
A function called parse_count may raise ValueError on invalid text and return an integer for valid text, including zero. Returning zero on failure would lose that distinction. Test how the caller handles invalid input as well as whether the function computes the expected value on good input.
Look for the boundary that defines one job
If a function normalizes input, calls a remote service, formats a table, and writes a file, it has four reasons to change. Start by separating the calculation from effects. The resulting smaller function can be exercised with literal inputs and exact expected output. Leave related operations together when splitting them would only create more names and no clearer contract.
A useful function test includes its ordinary result, its boundaries, and the state of any object it received. Call it twice when it has defaults or stores something between calls. You may catch shared state on the second call even when the first one looks correct.
Make scope and dependencies visible
A function can read names from outside its body. That is convenient for a shared constant, such as the fixed number of seconds in a minute. A value that changes according to the current user or environment is easier to reason about when it is an input. Consider a formatter that reads the name of the active report from a module-level variable. Callers using it in two jobs must coordinate who sets that name and when. Passing the name into the function gives each call its own explicit value.
Python also treats names assigned inside the body as local unless a declaration specifies another scope. A read placed before the first local assignment can raise UnboundLocalError even if a global name happens to exist. When a function would benefit from reading and updating a count, returning the new count often gives a cleaner interface than changing hidden state. A caller can inspect the returned value and decide where it belongs.
Use precise results when a Boolean is too small
When a check has only two meaningful outcomes, a Boolean result is natural. A function called is_ready can return True or False. A function that validates a field, however, may need to explain why it was rejected. Consider returning a result with useful context, or raising a specific exception when rejection means the operation cannot continue.
def split_tag(text):
name, separator, value = text.partition("=")
if not separator or not name.strip():
raise ValueError("Expected a nonblank name followed by '='")
return name.strip(), value.strip()
field, value = split_tag("title=Draft = version two")
assert (field, value) == ("title", "Draft = version two")
The first equals sign separates the name from the value. Any later equals signs belong to the value. split_tag("title=") returns a blank value, while split_tag("title") raises ValueError. Put that distinction in the docstring so a caller knows what the parser accepts.
When a function serves several callers, check at least one example from each place that uses it. A configuration editor may allow a blank value during a draft, while a publishing step may require a value. Both can share the parser. Each caller then owns its validation rule. That arrangement keeps parsing from silently choosing the policy of whichever caller happened to be written first. If every caller eventually enforces the same extra rule, consider making that a separate named check they can share.