Search code examples
python-3.xfirst-class-functions

The vocabulary of first class functions


When people say that Python, for instance, has first class functions, it makes it sound like Python also has second class functions. However, I've never yet (knowingly) encountered a second class function in Python. When we say this, does it really mean "All Python functions are first class?" Or is there an example of a second class function in Python?


Solution

  • First, to clarify the nomenclature.

    The term "first class functions" means that it is "first class" in the type system: that is, that functions themselves are values. In languages where functions are not first class, functions are defined as a relationship between values, which makes them "second class".

    Put another way, "first class" functions implies that you can use a function as a value, which means (among other things) that you can pass functions into functions. You couldn't do this in Java before Java 7 (reflection doesn't count), so that's an example of a programming language only having "second class" functions. In order to "pass a function", you had to define a type where that function could live (as a method), and then pass an instance of that type.

    So, in Python, all functions are first class, because all functions can be used as a value.

    Now, there is another concept which you might be getting confused with. There is also a concept of a "higher order function". A higher order function is a function that takes a function as an argument. Not all functions in Pythons are higher-order, because not all functions take another function as an argument. But even the functions that are not higher-order are first class. (It's a square/rectangle thing.)