Closures & Higher-Order Functions
Closures capture variables from their enclosing scope. Higher-order functions take functions as arguments or return functions.
15 min•By Priygop Team•Updated 2026
Closures & HOF
Closures & HOF
# Closure — function remembers its environment
def make_multiplier(factor):
def multiply(x):
return x * factor # 'factor' is captured!
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
# Higher-order functions
def apply(func, items):
return [func(x) for x in items]
numbers = [1, -2, 3, -4, 5]
print(apply(abs, numbers)) # [1, 2, 3, 4, 5]
print(apply(str, numbers)) # ['1', '-2', '3', '-4', '5']
# map, filter, reduce
from functools import reduce
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
total = reduce(lambda a, b: a + b, nums)
print(f"Squared: {squared}")
print(f"Evens: {evens}")
print(f"Sum: {total}")
# Function factory
def make_validator(min_val, max_val):
def validate(value):
return min_val <= value <= max_val
return validate
age_valid = make_validator(0, 150)
score_valid = make_validator(0, 100)
print(age_valid(25)) # True
print(score_valid(150)) # FalseTip
Tip
Use type hints for better IDE support and documentation: def greet(name: str) -> str:. Use mypy for static type checking.
Diagram
Loading diagram…
Closure = function + its lexical scope
Common Mistake
Warning
Type hints are NOT enforced at runtime. They're for documentation and tools only. int('hello') still raises ValueError.
Quick Quiz
Practice Task
Note
(1) Add type hints to 5 functions. (2) Use Optional[] and Union[]. (3) Run mypy to check types.