Skip to Content
Fluent Python
book

Fluent Python

by Luciano Ramalho
August 2015
Intermediate
790 pages
18h 48m
English
O'Reilly Media, Inc.
Content preview from Fluent Python

Chapter 5. First-Class Functions

I have never considered Python to be heavily influenced by functional languages, no matter what people say or think. I was much more familiar with imperative languages such as C and Algol 68 and although I had made functions first-class objects, I didn’t view Python as a functional programming language.1

Guido van Rossum, Python BDFL

Functions in Python are first-class objects. Programming language theorists define a “first-class object” as a program entity that can be:

  • Created at runtime

  • Assigned to a variable or element in a data structure

  • Passed as an argument to a function

  • Returned as the result of a function

Integers, strings, and dictionaries are other examples of first-class objects in Python—nothing fancy here. But if you came to Python from a language where functions are not first-class citizens, this chapter and the rest of Part III of the book focuses on the implications and practical applications of treating functions as objects.

Tip

The term “first-class functions” is widely used as shorthand for “functions as first-class objects.” It’s not perfect because it seems to imply an “elite” among functions. In Python, all functions are first-class.

Treating a Function Like an Object

The console session in Example 5-1 shows that Python functions are objects. Here we create a function, call it, read its __doc__ attribute, and check that the function object itself is an instance of the function class.

Example 5-1. Create and ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Fluent Python, 2nd Edition

Fluent Python, 2nd Edition

Luciano Ramalho

Publisher Resources

ISBN: 9781491946237Errata Page