Use this when writing small, typed and testable Python functions for automation.
Functions · Python Automation
Python functions are defined with def, take positional and keyword arguments and return values. Small, focused functions with type hints make automation code easier to test and reuse.
1. Functions: single purpose, typed parameters, return values, docstrings.
2. Avoid global state.
3. Raise exceptions on errors.
4. Test with pytest.
5. Keep short.
inputs → function → output/exception
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 Verification path Verify boundary
The negative fixture should deliberately exercise risks such as environment drift, implicit coercion, broad exception handling, blocking/async confusion, shell quoting/subprocess risks, partial writes and non-deterministic external APIs, choosing the cases most relevant to parameter/return contracts, scope, side effects, exceptions/exit behavior and unit-testable boundaries rather than hidden global state.
Step 2 Example Narrow the fault
def interface_down(ifaces: list[dict]) -> list[str]:
return [i["name"] for i in ifaces if i["oper_status"] != "up"]
Step 3 Common mistakes Narrow the fault
- Functions that print instead of returning.
- Mutable default arguments (
def f(items=[])).
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
- Small, focused functions are easier to test.
- Type hints document inputs and outputs.
- Return values instead of printing.
python3 -c 'import inspect, m; print(inspect.signature(m.f))'— signature- Docstrings — documentation
pytest -k <function>— unit tests
ReferenceWhy it matters1 section · depth on demand
What it is
Functions package a piece of logic with inputs (parameters) and an output (return value). Small functions with clear inputs are easier to test and reuse across scripts.
ReferenceImportant terms & boundaries2 sections · depth on demand
In depth
Functions package a piece of logic under a name with inputs (parameters) and an output (return value). In automation they turn long scripts into readable building blocks — connect, collect, render, push, verify — that can be tested individually and reused.
def vlan_diff(current: dict[int, str], desired: dict[int, str]) -> tuple[dict, set]:
"""Return VLANs to add/change and VLAN IDs to remove."""
to_set = {vid: name for vid, name in desired.items() if current.get(vid) != name}
to_remove = set(current) - set(desired)
return to_set, to_remove
Good functions do one thing, take their inputs as parameters instead of reading globals, return data rather than printing it, and have type hints and a docstring. Pure functions like the one above are easy to unit test because they do not touch devices.
Mechanics
The linked authority for bounded mechanics is Python Documentation — Defining Functions; documentation support is separate from observed lab/production Evidence.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Python Automation > Functions. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://docs.python.org/3/tutorial/controlflow.html#defining-functions · confidence 94%Deep reference
Healthy vs suspicious evidence
Output interpretation
For parameter/return contracts, scope, side effects, exceptions/exit behavior and unit-testable boundaries rather than hidden global state, prefer typed fields and stable IDs over human presentation text.