A function is an object that can be stored, passed and returned without immediately calling it.
Python first-class functions: dispatch through an explicit operation registry
Operation contract
The receipt dispatcher maps two accepted operation names to functions and invokes only the selected handler. It validates the operation and exact nonnegative integer amount before calling the registry entry. A named registry keeps accepted behavior visible; it does not need eval, a received import path or a chain of guessed method names. A returned closure retains its declared fee.
Failure and ownership boundary
Passing a function differs from passing its result. A registry also retains its callable objects, including any state captured by closures. Callbacks can perform side effects, so selecting an accepted name alone is not a transaction. Python closures: capture loop values at the intended time, Python lambda functions: one expression and the same closure rules and Python plugin project: load owned code and publish only an accepted interface cover adjacent contracts.
Working program
def charged_amount(amount):
return amount + 25
def refunded_amount(amount):
return amount
HANDLERS = {"charge": charged_amount, "refund": refunded_amount}
def dispatch(operation, amount):
if not isinstance(operation, str) or operation not in HANDLERS:
raise ValueError("operation rejected")
if type(amount) is not int or not 0 <= amount <= 1000000:
raise ValueError("amount rejected")
return HANDLERS[operation](amount)
def with_fee(fee):
def charge(amount):
return amount + fee
return charge
print(dispatch("charge", 125))
print(dispatch("refund", 125))
print(with_fee(40)(125))
try:
dispatch("__import__", 125)
except ValueError:
print("unknown operation rejected")Output
150
125
165
unknown operation rejectedCosts and limits
Expected registry lookup work is constant for suitable string hashes; handler cost is separate. The fixed registry retains two functions. Each returned closure retains its fee until the closure is released.
Common Mistakes
- Pass a callback object when the caller must choose its execution time.
- A received operation name must not become executable source or an unrestricted import.
Connected lessons
Python functions: define units, validate input and return a result, Python closures: capture loop values at the intended time, Python plugin project: load owned code and publish only an accepted interface.
Follow the ownership and update boundary
Python singledispatch: dispatch follows the first argument’s type.
