Book Image

Functional Python Programming

By : Steven F. Lott, Steven F. Lott
Book Image

Functional Python Programming

By: Steven F. Lott, Steven F. Lott

Overview of this book

Table of Contents (23 chapters)
Functional Python Programming
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

First-class functions


Functional programming is often succinct and expressive. One way to achieve this is by providing functions as arguments and return values for other functions. We'll look at numerous examples of manipulating functions.

For this to work, functions must be first-class objects in the runtime environment. In programming languages such as C, a function is not a runtime object. In Python, however, functions are objects that are created (usually) by the def statements and can be manipulated by other Python functions. We can also create a function as a callable object or by assigning lambda to a variable.

Here's how a function definition creates an object with attributes:

>>> def example(a, b, **kw):
...    return a*b
...
>>> type(example)
<class 'function'>
>>> example.__code__.co_varnames
('a', 'b', 'kw')
>>> example.__code__.co_argcount
2

We've created an object, example, that is of class function(). This object has numerous attributes...