Delete Set public Set private Add tags Delete tags
  Add tag   Cancel
  Delete tag   Cancel
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Login

Python Functions Are First‑Class Citizens/shaare/AumOhg

  • python
  • python

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
1 month ago Permalink
cluster icon
  • Lambda Functions : Lambda Functions Python functions defined with def allow multiple statements, clear naming, and support for docstrings, making them ideal for complex...
  • Variables, comments : Variables: Naming Values Naming Guidelines: Must start with a letter or underscore (_) and can contain letters, numbers, and underscores. Use snake_...
  • The Iteration Protocol : The Iteration Protocol We use for item in sequence: all the time. But how does Python get each item? Iterable: An object that can be looped over. It...
  • Generics typing : Introduction to Generics Generic types let you write reusable, type-safe functions and classes that work uniformly across different data types. They ...
  • Parametrized Tests : Parametrized Tests Introduction Often, we need to test the same logic with different inputs and outputs, such as validating various IP address or hos...


(97)
Filter untagged links
Fold Fold all Expand Expand all Are you sure you want to delete this link? Are you sure you want to delete this tag? The personal, minimalist, super-fast, database free, bookmarking service by the Shaarli community