Python Functions Are First‑Class Citizens/shaare/AumOhg
Python Functions Are First‑Class Citizens
-
In Python, functions behave like any other object (strings, ints, lists).
-
Because they are "first‑class", we can:
- Bind them to new variable names
- Pass them around as arguments
- Return them from other functions
- Stash them in data structures.
-
This flexibility is the foundation for patterns such as callbacks, plugin registries, and decorators.
-
Assigning Functions to Variables
-
A variable can reference the function object itself, not its return value.
-
Any name that points to the function can be used to call it.
-
This is handy for creating aliases or late‑binding a function into another module.
def greet(name):
print(f"Hello, {name}!")
say_hello = greet
print(say_hello is greet)
say_hello("Alice")
Passing Functions as Arguments
- Higher‑order functions accept other callables to customize behavior.
- Classic examples:
sorted(key=...), event callbacks, retry helpers. - Lets you build flexible pipelines without hard‑coding every step.
def apply_operation(operation, *operands):
print(f"Applying {operation.__name__} to {operands}")
return operation(*operands)
def add(*numbers):
return sum(numbers)
def mul(*numbers):
result = 1
for n in numbers:
result *= n
return result
print(apply_operation(add, 1, 2))
print(apply_operation(mul, 1, 2, 3, 4))
Returning Functions from Functions
- A factory function can create and return a new, customized function.
- The returned function “remembers” variables from the factory’s scope: this is a closure.
- Great for building tailored validators, loggers, or API clients on the fly.
def create_api_client(auth_token):
def api_client(endpoint, method):
return f"Hitting endpoint {endpoint} with method {method} and auth token {auth_token}"
return api_client
alice_api_client = create_api_client("alice-token")
bob_api_client = create_api_client("bob-token")
print(alice_api_client("/users", "GET"))
print(bob_api_client("/health", "GET"))
Storing Functions in Data Structures
- Functions can live inside lists, dicts, sets, and other containers.
- Enables command dispatch tables, plugin registries, and processing pipelines.
def task_A():
print("Running task A")
def task_B():
print("Running task B")
def task_C():
print("Running task C")
pipeline = [task_B, task_A, task_C]
for task in pipeline:
task()
command_registry = {
"start": task_A,
"process": task_B,
"stop": task_C
}
command_registry["process"](http://)
Why First‑Class Functions Matter for Decorators
- Decorators are simply functions that take another function, wrap it, and return a new function.
- That entire mechanism only works because Python lets us treat functions as data.
- With this groundwork, we’re ready to explore decorator syntax (
@decorator) next.
python
(97)