Nested Functions

Concepts covered: Scope

A def can sit inside another function's body. Python executes that inner def each time the outer function runs, building a fresh function object and binding it to a local name. Like every local, the name goes away when the outer function returns, so no other code in the module can call the helper.

def clean_emails(raw_emails, domain):
    def normalize(email):
        return email.lower().replace(" ", "")

    def belongs(email):
        return email.endswith("@" + domain)

    cleaned = map(normalize, raw_emails)
    return list(filter(belongs, cleaned))

raw = [" Ana@Shop.io", "bo@other.com", "CY@shop.io "]
print(clean_emails(raw, "shop.io"))

Output:

['ana@shop.io', 'cy@shop.io']

normalize and belongs exist only while clean_emails runs, so anyone reading the module sees a single public function. belongs also uses domain without receiving it as a parameter: it reads the variable from the function it sits inside. That keeps belongs at 1 parameter, which is what filter passes per item.

Written at module level, belongs would need domain as a second parameter, and you would bridge the gap with partial(belongs, domain=domain). The nested version reaches the same result by reading domain from the scope around it.

How Python finds a name

When a nested function uses a name, Python searches 4 scopes in order and stops at the first match: the inner function's own local names, then the enclosing function's names, then the module's global names, then Python's built-in names such as len and print. Local and global are familiar from earlier work. Enclosing is the layer nesting adds.

ScopeWhere the name is assignedExample from the email code
LocalIn the inner function itself`email`, inside `belongs`
EnclosingIn the function around it`domain`, read by `belongs`
GlobalAt the top level of the module`raw`
Built-inSupplied by Python`map`, `filter`, `list`

Assigning creates a new local

Reading an enclosing name needs no declaration. Assigning to it behaves differently: an assignment anywhere in the inner function makes that name belong to the inner function for its whole body, and the enclosing variable keeps its value.

def summarize(rows):
    count = len(rows)

    def label():
        count = 99
        return f"{count} rows"

    text = label()
    return text, count

print(summarize([4, 8, 15]))

Output:

('99 rows', 3)

label gets its own count, set to 99, while the count in summarize stays 3. Rebinding the enclosing variable takes a keyword of its own, which arrives with closures.

What happens when this runs?

def load(rows):
    def is_valid(row):
        return row["id"] is not None
    return list(filter(is_valid, rows))

print(len(load([{"id": 1}, {"id": None}])))
print(is_valid({"id": 2}))

When to nest and when not to

Do
  • Nest a helper that only 1 function uses and that reads that function's parameters
  • Nest to hand map, filter or sorted a 1-argument function built from outer values
  • Keep nested helpers to a few lines so the outer function stays readable
Avoid
  • Don't nest a helper you want to test alone; a test can't reach a local function
  • Don't nest logic that 2 functions need; move it to module level
  • Don't stack 3 levels of nesting; every level adds a scope to track

Python builds a fresh function object for each nested def every time the outer function runs. The cost is small, but for a function called millions of times inside a loop, a module-level helper skips it.

About this lesson

This section is part of the Functional Programming: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.