First Class Function
In Python, functions are first-class objects. This means a function can be assigned to a variable, stored in a data structure, passed as an argument to ano...
Functions as First-Class Objects
In Python, functions are first-class objects. This means a function can be assigned to a variable, stored in a data structure, passed as an argument to another function, and returned from a function — exactly the same as any other value like an integer or string. This capability enables powerful programming patterns including higher-order functions, decorators, callbacks, and functional programming styles.
Assigning Functions to Variables
You can assign a function to a variable without calling it by omitting the parentheses: def square(x): return x**2; f = square. Now f and square refer to the same function object. Calling f(5) gives 25. This is useful for aliasing long function names or selecting functions at runtime. You can confirm both names point to the same object by checking square is f, which returns True.
Passing Functions as Arguments
A function that accepts another function as an argument is called a higher-order function. The built-in map(), filter(), and sorted() all accept functions as arguments. Custom example: def apply(func, value): return func(value); apply(str.upper, "hello") returns "HELLO". This pattern is used in callbacks (event handlers, timers), pipelines, and testing frameworks that accept assertion functions. Passing functions as arguments is the foundation of the strategy design pattern.
Returning Functions
A function can return another function. This is how factory functions and decorators work. def multiplier(factor): def inner(x): return x * factor; return inner. double = multiplier(2); triple = multiplier(3); double(5) gives 10; triple(5) gives 15. Each call to multiplier creates a new inner function that closes over a different value of factor. The returned functions are independent and carry their own captured environment.
Storing Functions in Data Structures
Because functions are objects, they can be stored in lists, tuples, or dictionaries. dispatch = {"add": lambda a, b: a+b, "sub": lambda a, b: a-b}; result = dispatch["add"](3, 4) gives 7. This dispatch table pattern replaces long if-elif chains and is both more extensible and faster. You can add new operations by inserting into the dictionary without modifying existing code — a direct application of the Open/Closed Principle.
Exam Tip
First-class function questions often ask: what does it mean for functions to be first-class? The answer must include: assignable to variables, passable as arguments, returnable from functions. Examiners also ask: what is a higher-order function? A function that takes a function as input or returns a function as output (or both). Know that map, filter, sorted, and any decorator are all examples of higher-order functions. Being able to name concrete examples elevates your answer from theoretical to practical.