Adding First-class Functions to Python
Let’s pretend we are stuck in an alternate universe where first-class functions1 don’t exist in Python. How could we add them back in using classes, without modifying the run-time?
Here’s a square function:
class SquareFunc: def apply(x): return x * x square = SquareFunc()
Okay, that wasn’t very exciting. What about higher-order functions?
class MapFunc: def apply(f, list): new_list =  for element in list: new_list.append(f(element)) return new_list map = MapFunc() map.apply(square, [1, 2, 3]) # [1, 4, 9]
And that’s it!
Or list comprehensions, as that would be cheating for this example. Also, I’m pretending
__call__doesn’t exist. Because.↩