Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question

What does it mean that functions are first-class objects in Python, and what is a higher-order function?

Answer

Being first-class means a function is a regular object like any other value: it can be assigned to a variable, stored in a list or dict, passed as an argument, returned from another function, and inspected for attributes like `__name__` and `__doc__`. A higher-order function is any function that takes another function as an argument, returns a function, or both — `map()`, `sorted(key=...)`, and decorators are all higher-order functions that rely directly on functions being first-class.

Strong answer includes

  • functions can be assigned, stored, passed and returned like any value
  • higher-order function takes and/or returns a function
  • decorators, map, and sorted(key=) are concrete examples

Practical example

Python example
operations = {"add": lambda a, b: a + b, "sub": lambda a, b: a - b}

stores functions as dict values and looks one up by name at runtime with

Python example
operations["add"](2, 3)

.

#functions#functional-programming

Sources

The Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics