Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • Tags
  • Connexion

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
3 months ago Permalien
cluster icon
  • 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...
  • Logging Anatomy : Python Logging Anatomy Python’s logging module has five core components: Loggers, Log Records, Handlers, Formatters and Filters. Loggers are hierar...
  • Filesystem Paths : Working with Filesystem Paths in Python Manipulating paths as plain strings is error-prone and OS-specific. pathlib provides an object-oriented, cr...
  • Fixtures in Pytest : Fixtures in Pytest As tests grow more complex, repeating setup and cleanup steps makes tests harder to read and maintain. Pytest fixtures allow centr...
  • Editable Installs with pyproject.toml : Editable Installs with pyproject.toml The Python interpreter doesn't automatically know about our project's structure. The modern and most robust solu...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli