Functions In Depth
Functions are first-class objects
Section titled “Functions are first-class objects”In Python, functions are values — not special syntax, not second-class constructs. A function can be assigned to a variable, stored in a list, passed as an argument, or returned from another function. This property is called first-class status, and it is the foundation of every advanced pattern in this module.
def greet(name: str) -> str: return f"Hello, {name}!"
# Assign to a variablesay_hi = greet
# Pass as an argumentdef apply(fn, value): return fn(value)
result = apply(greet, "Python")print(result) # Hello, Python!Because greet is just an object, say_hi and greet point to the same function.
Calling say_hi("World") is identical to calling greet("World").
What this module covers
Section titled “What this module covers”| Lesson | Core concept |
|---|---|
| Args & Kwargs | Positional, keyword, variadic, and keyword-only parameters |
| Closures | Nested functions, free variables, and nonlocal |
| Decorators | Functions that wrap other functions; functools.wraps |
| Generators | yield, lazy evaluation, and StopIteration |
Each lesson is self-contained and builds on this foundation: functions are objects you can manipulate freely.
A first runnable demo
Section titled “A first runnable demo”The snippet below demonstrates two core ideas simultaneously: passing a function as an argument, and returning a function as a value.
def make_multiplier(factor: int): def multiply(x: int) -> int: return x * factor return multiply
double = make_multiplier(2)triple = make_multiplier(3)
numbers = [1, 2, 3, 4, 5]doubled = list(map(double, numbers))tripled = list(map(triple, numbers))
print("doubled:", doubled)print("tripled:", tripled)
# Functions are objects — we can store them in a listops = [double, triple, make_multiplier(10)]for op in ops: print(op(7))Loading Python runtime (first run only)…