Lesson · Functional Programming Tools
Functions as First-Class Objects
55 min readFunctions as First-Class Objects
Functions are first-class objects: they can be stored, passed, returned, and selected at runtime. This enables callbacks, strategies, decorators, and functional composition.
Learning goals
- Tell the difference between passing a function object and passing the result of calling it.
- Use a function as an argument and explain who calls it, when, and how often.
- Return a function from another function and show that the caller receives the function object, not its result.
- Store callables in a list or dictionary and select behavior by key instead of a chain of branches.
- Explain how callbacks and strategy selection reuse the same mechanism under different names.
Mental model
A function object travels exactly like any other value: into a call as an argument, out of a call as a return value, and into a container as an entry. What makes callables special is not how they move but what happens afterward: the code that receives one decides when to invoke it. Callbacks and strategy selection are that single idea under different names.
Core idea
Once functions are values, behavior becomes data you can choose, store, and pass around. In the worked example, apply_twice never mentions exclaim; it receives whatever callable the caller supplies and applies it twice. Callback registration and strategy selection are the same mechanism applied to scheduling and configuration.
Passing functions
A function object can be passed as an argument because it is an ordinary value: apply_twice(exclaim, greet("Ada")) hands exclaim itself to apply_twice while greet("Ada") is evaluated first. The receiver decides when and how often to call it, so the same argument can run once, twice, or never.
Returning functions
A function can return another function object, which lets a factory decide behavior when it is called rather than when it is defined. The returned function keeps access to the enclosing call's bindings when its body uses them, so one definition can produce configured variants.
Storing callables
Callables can live in lists, dictionaries, and attributes, so behavior can be selected by lookup instead of a long if/elif chain. A dictionary from command names to functions, for example, replaces branching with one key access and one call.
Callbacks
A callback is a callable supplied now and invoked later by another component. Document when it runs, what arguments it receives, and how its exceptions are handled.
Strategy selection
A strategy is interchangeable behavior selected behind one interface. Passing a function or collaborator often expresses this pattern without an inheritance hierarchy.
Walkthrough
greet("Ada")is evaluated beforeapply_twiceruns, so the inner argument is the string"Hello, Ada", while the outer argument is the function objectexclaim.- Inside
apply_twice, the parameterfnholds that function object. The body evaluatesfn(value)first, producing"Hello, Ada!", then appliesfnto that text and adds the second!. - The final print receives
"Hello, Ada!!". The nameexclaimis never visible insideapply_twice, which is the proof that the function traveled as a value. - Predict before running: what exactly is passed for
fn, and how many times doesexclaimrun?
Experiments to try
- Call
apply_twice(greet, "Ada")and predict the result first:greetis applied to its own output, so the greeting nests. - Define
def shout(text): return text.upper()afterapply_twiceand pass it in; check that the callee accepts the new function without any change. - Store
[greet, exclaim]in a list and callfunctions[0]("Ada"); then build{"greet": greet, "exclaim": exclaim}and call the entry by key. - Print
type(exclaim)andexclaim.__name__, then assignalias = exclaimand comparealias is exclaim; explain what the function object carries with it.
Common mistakes
- Calling the function at the argument position (
apply_twice(exclaim("Ada"), "Ada")) when the callee expects the function itself; the parentheses run it immediately and pass its result. - Passing a string or number where a callable is required and meeting
TypeError: 'str' object is not callableonly when the callee invokes it, which can be far from the call site. - Confusing
fnwithfn()inside a higher-order function body:fnis the object,fn()is one invocation, and the number of invocations is the callee's choice. - Reaching for a class hierarchy when a function parameter would do: strategy selection needs only a shared call signature, so an extra class adds structure without adding behavior.
Practice: Easy
- Call
apply_twicewithexclaimand with a new function that appends?; record the two outputs and point to the line that supplies each behavior. - Replace the inner
greet("Ada")withapply_twice(greet, "Ada")and write down why the greeting nests (greetreceives"Hello, Ada"from the first pass). - Assign
f = exclaim, passftoapply_twice, and verify the result matches the original run; state what changed and what did not.
Practice: Medium
- Build a calculator over a list of
(symbol, a, b)tuples: map"+","-", and"*"tooperator.add,operator.sub, andoperator.mul, then apply the selected function. State what each dictionary entry stores. - Write
make_multiplier(n)that returns a function multiplying byn; call it twice with different factors and show that the two callables do not interfere. - Turn a three-branch if/elif on a command name into a dictionary of callables with one default entry; describe what happens when the key is missing and how you would report it.
Practice: Hard
- Design a small event registry:
on(event, handler)stores handlers in a dictionary,emit(event, *args)calls each handler, and one handler that raises must not stop the others. Define the return value and the failure policy before coding. - Extend
apply_twiceintoapply_n(fn, value, n), then use it to run a pipeline[str.strip, str.lower]in order on" PYTHON "; state where the function objects live and whatapply_nreceives. - Compare two strategy designs for a shipping-cost rule (a dictionary of functions against a subclass per rule) on lookup cost, testability, and the cost of adding a rule; pick one and justify the choice.
Lesson checklist
- I can point to the difference between passing
exclaimand passingexclaim("Ada")in a call. - I can write a function that accepts a callable and calls it a chosen number of times.
- I can return a function from a factory and show that two results of the factory stay independent.
- I can replace a multi-branch selection with a dictionary of functions and name the tradeoff.
Remember
A function is an object, so passing, returning, and storing one are ordinary object operations with one extra consequence: whoever receives the function decides when it runs. `apply_twice` shows the mechanism in a few lines, and callbacks plus strategy selection are that same idea scaled up. Keep the parentheses straight: `fn` is a value, `fn()` is a call.
Interview angles
What is the main purpose of **Passing functions**?+
A function object can be passed as an argument because it is an ordinary value: apply_twice(exclaim, greet("Ada")) hands exclaim itself to apply_twice while greet("Ada") is evaluated first. The receiver decides when and how often to call it.
What should you pay attention to when using **Returning functions**?+
A function can return another function object, which lets a factory decide behavior when it is called rather than when it is defined. The returned function keeps access to the enclosing call's bindings when its body uses them.
How does **Storing callables** fit into this lesson?+
Callables can live in lists, dictionaries, and attributes, so behavior can be selected by lookup instead of a long if/elif chain. A dictionary from command names to functions replaces branching with one key access and one call.
Why does `apply_twice(exclaim("Ada"), "Ada")` raise `TypeError`?+
exclaim("Ada") runs immediately and returns the string "Ada!". apply_twice then expects a callable in fn and tries fn(fn(value)), and invoking a str raises TypeError: 'str' object is not callable.