Python for AI Engineers · Part A · Lesson 4 of 26

Python functions, closures and decorators

How Python functions really work for a developer coming from Java or JavaScript: default and keyword arguments, the mutable default trap, *args and **kwargs, functions as values, closures, and decorators. You will finish by writing the @retry decorator every LLM app needs.

⏱ 35 min3 exercises that check your codeRuns in your browser

By the end you can

  • Call functions with positional, keyword and default arguments, and avoid the mutable default trap
  • Accept any arguments with *args and **kwargs, and forward them
  • Pass functions around as values and build closures
  • Write and use decorators, including a @retry with backoff for flaky API calls
1 / 5

1Defining and calling functions

A function starts with def, has no braces, and its body is the indented block. Type hints after the parameters and -> are optional and not checked at run time, but they document the function and let your editor catch mistakes.

Python is stricter than JavaScript about arguments: calling with a missing or extra argument is an error, not undefined. And any argument can be passed by name, which makes calls with several options readable.

Try it: edit and run
def price(tokens: int, per_million: float = 0.15) -> float:
    """Dollar cost of a number of tokens."""
    return tokens * per_million / 1_000_000


print(price(2000))                     # uses the default rate
print(price(2000, 3.0))                # positional
print(price(per_million=3.0, tokens=2000))  # by name, any order
Expected output
0.0003
0.006
0.006

Tip Pass options by name (timeout=30) whenever a call has more than two arguments. Readers do not have to remember the order.

2The mutable default trap

Default values are created once, when the function is defined, not on every call. For numbers and strings that never matters. For a list or dict it is a classic bug: every call shares the same list.

Try it: edit and run
def add_message(text, history=[]):      # the bug: one list shared by every call
    history.append(text)
    return history


print(add_message("hi"))
print(add_message("hello"))   # surprise: the first message is still there


def add_message_fixed(text, history=None):
    if history is None:                # a fresh list on each call
        history = []
    history.append(text)
    return history


print(add_message_fixed("hi"))
print(add_message_fixed("hello"))
Expected output
['hi']
['hi', 'hello']
['hi']
['hello']

Watch out This bug leaks one user's chat history into another user's request. Always use None as the default for lists, dicts and sets.

3*args and **kwargs

*args collects extra positional arguments into a tuple, **kwargs collects extra keyword arguments into a dict. You see them in every wrapper: a function that takes "whatever" and passes it on to another function.

The same stars work the other way when calling: f(*items) spreads a list into positional arguments and f(**options) spreads a dict into keyword arguments, like ... in JavaScript.

Try it: edit and run
def log_call(name, *args, **kwargs):
    print("calling", name, "with", args, kwargs)


log_call("chat", "What is DNS?", temperature=0.2, max_tokens=100)

options = {"temperature": 0.7, "max_tokens": 50}
log_call("chat", *["Hello", "World"], **options)
Expected output
calling chat with ('What is DNS?',) {'temperature': 0.2, 'max_tokens': 100}
calling chat with ('Hello', 'World') {'temperature': 0.7, 'max_tokens': 50}

4Functions are values

A function is an object like any other: you can store it in a variable or a dict, pass it to another function, and return it. That is what makes the next two ideas possible.

A dict of functions is a neat replacement for a long if / elif chain. It is exactly how an agent maps a tool name the model asked for to the code that runs it.

Try it: edit and run
def get_weather(city):
    return f"Sunny in {city}"


def get_time(city):
    return f"10:42 in {city}"


TOOLS = {"get_weather": get_weather, "get_time": get_time}

requested = {"name": "get_time", "args": {"city": "Pune"}}   # what a model might ask for
fn = TOOLS[requested["name"]]
print(fn(**requested["args"]))
Expected output
10:42 in Pune

Tip You will use this exact pattern in the tool calling lab: the model returns a tool name and arguments, and a dict lookup runs the right function.

5Closures: functions that remember

A function defined inside another function can use the outer function's variables, and keeps them after the outer function has returned. That is a closure. It is a lightweight way to make a configured function without writing a class.

To change an outer variable (not just read it), declare it nonlocal.

Try it: edit and run
def make_counter():
    count = 0

    def next_id():
        nonlocal count          # we assign to the outer variable
        count += 1
        return f"req-{count}"

    return next_id


new_id = make_counter()
print(new_id(), new_id(), new_id())
other = make_counter()          # a separate counter with its own count
print(other())
Expected output
req-1 req-2 req-3
req-1

6Decorators: wrapping a function

A decorator is a function that takes a function and returns a new function that usually calls the original, adding something before or after. @timed above a def is just shorthand for slow = timed(slow).

functools.wraps copies the original name and docstring onto the wrapper, so logs and error messages still show the real function name.

Try it: edit and run
import functools
import time


def timed(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = fn(*args, **kwargs)
        ms = (time.perf_counter() - start) * 1000
        print(f"{fn.__name__} took {ms:.0f} ms")
        return result
    return wrapper


@timed
def slow_answer(question):
    time.sleep(0.2)
    return "42"


print(slow_answer("meaning of life?"))
Expected output
slow_answer took 200 ms
42

7A decorator with options: @retry

Model APIs fail now and then: timeouts, rate limits, a busy server. The fix is to retry with a growing wait (exponential backoff) and a little randomness (jitter) so many clients do not retry at the same instant.

A decorator that takes options needs one more layer: retry(times=3) returns the actual decorator. Read it from the outside in.

Try it: edit and run
import functools
import random
import time


def retry(times=3, base=0.5, on=(TimeoutError, ConnectionError)):
    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return fn(*args, **kwargs)
                except on as e:
                    if attempt == times:
                        raise
                    wait = base * 2 ** (attempt - 1) + random.uniform(0, 0.1)
                    print(f"attempt {attempt} failed ({e}); retrying in {wait:.2f}s")
                    time.sleep(wait)
        return wrapper
    return decorator


calls = {"n": 0}


@retry(times=3, base=0.1)
def flaky_llm_call(prompt):
    calls["n"] += 1
    if calls["n"] < 3:
        raise TimeoutError("model took too long")
    return f"answer to {prompt!r}"


print(flaky_llm_call("hi"))
Expected output
attempt 1 failed (model took too long); retrying in 0.13s
attempt 2 failed (model took too long); retrying in 0.25s
answer to 'hi'

Only retry errors that can succeed next time (timeouts, rate limits, 5xx). Retrying a bad request or a wrong key just wastes time. The SDK in the labs already retries for you; you will still write this for your own tools and services.

Common mistakes

  • Using a list or dict as a default argument (def f(x, items=[])): it is shared by every call. Default to None.
  • Forgetting return in a decorator's wrapper, so the decorated function suddenly returns None.
  • Skipping @functools.wraps: logs and tracebacks then show wrapper instead of the real name.
  • Assigning to an outer variable inside a closure without nonlocal, which raises UnboundLocalError.
  • Retrying every exception, including bugs and bad input. Retry only errors that can succeed on a second try.

Practice

Write the code, then press Check. Your work is saved in this browser.

1Fix the shared default

add_tag should return a new list each time it is called without tags. Fix it without changing how it is called.

Exercise
def add_tag(tag, tags=[]):
    tags.append(tag)
    return tags


print(add_tag("python"))
print(add_tag("ai"))
Hint

Default to None, and create the list inside the function when it is None.

2Write @count_calls

Write a decorator count_calls that counts how many times the decorated function has been called and stores the number in an attribute calls on the wrapper. The function must still return its normal result.

Exercise
import functools


def count_calls(fn):
    # your code here
    ...


@count_calls
def greet(name):
    return f"Hello {name}"


print(greet("Asha"), greet("Ben"), greet.calls)
Hint

Inside the wrapper do `wrapper.calls += 1` before calling fn. Set `wrapper.calls = 0` after defining the wrapper.

3Backoff waits

Write backoff_waits(times, base) that returns the list of waits (in seconds, no jitter) a retry loop makes before each retry: attempt 1 fails, wait base; attempt 2 fails, wait base * 2; and so on. With times attempts there are times - 1 waits.

Exercise
def backoff_waits(times, base):
    # your code here
    return []


print(backoff_waits(4, 0.5))
Hint

The wait before retry number k (starting at 1) is base * 2 ** (k - 1).

Interview questions

Q1Why are mutable default arguments dangerous in Python?

Defaults are evaluated once when the function is defined, so a list or dict default is shared by every call that uses it. Changes leak between calls. Use None and create the object inside the function.

Q2What are *args and **kwargs?

*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict. They are used to write wrappers that accept anything and forward it with fn(*args, **kwargs).

Q3What is a closure?

A function that uses variables from the function it was defined in and keeps them alive after that function returns. Use nonlocal to assign to such a variable.

Q4What is a decorator and what does functools.wraps do?

A decorator takes a function and returns a new function, usually a wrapper that adds behaviour around the original. @d above a def means f = d(f). functools.wraps copies the original name, docstring and attributes onto the wrapper.

Q5How would you add retries to a flaky API call?

Retry only transient errors (timeouts, 429, 5xx), a limited number of times, with exponential backoff plus jitter so clients do not retry in sync. Make the operation idempotent or use an idempotency key so a retried write does not happen twice.