Book Image

Functional Python Programming - Second Edition

Book Image

Functional Python Programming - Second Edition

Overview of this book

If you’re a Python developer who wants to discover how to take the power of functional programming (FP) and bring it into your own programs, then this book is essential for you, even if you know next to nothing about the paradigm. Starting with a general overview of functional concepts, you’ll explore common functional features such as first-class and higher-order functions, pure functions, and more. You’ll see how these are accomplished in Python 3.6 to give you the core foundations you’ll build upon. After that, you’ll discover common functional optimizations for Python to help your apps reach even higher speeds. You’ll learn FP concepts such as lazy evaluation using Python’s generator functions and expressions. Moving forward, you’ll learn to design and implement decorators to create composite functions. You'll also explore data preparation techniques and data exploration in depth, and see how the Python standard library fits the functional programming model. Finally, to top off your journey into the world of functional Python, you’ll at look at the PyMonad project and some larger examples to put everything into perspective.
Table of Contents (18 chapters)

Implementing more complex decorators


To create more complex functions, Python allows the following kinds of commands:

@f_wrap
@g_wrap
def h(x):
    something

There's nothing in Python to stop us from stacking up decorators that modify the results of other decorators. This has a meaning somewhat like

. However, the resulting name will be merely

. Because of this potential confusion, we need to be cautious when creating functions that involve deeply nested decorators. If our intent is simply to handle some cross-cutting concerns, then each decorator should be designed to handle a separate concern without creating much confusion.

If, on the other hand, we're using a decoration to create a composite function, it may also be better to use the following kinds of definitions:

from typing import Callable

m1: Callable[[float], float] = lambda x: x-1
p2: Callable[[float], float] = lambda y: 2**y
mersenne: Callable[[float], float] = lambda x: m1(p2(x))

Each of the variables has a type hint that defines...