Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (14 votes)
31 views

Download Complete (Ebook) Functional Python Programming...Efficient Python Code by Lott S. PDF for All Chapters

The document provides information about various Python programming ebooks available for download, including titles focused on functional programming, clean code, and optimization techniques. It highlights the versatility of Python and the benefits of functional programming, such as writing efficient and maintainable code. The document also includes details about the author and contributors, as well as a table of contents for the book 'Functional Python Programming.'

Uploaded by

dejvistapuro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (14 votes)
31 views

Download Complete (Ebook) Functional Python Programming...Efficient Python Code by Lott S. PDF for All Chapters

The document provides information about various Python programming ebooks available for download, including titles focused on functional programming, clean code, and optimization techniques. It highlights the versatility of Python and the benefits of functional programming, such as writing efficient and maintainable code. The document also includes details about the author and contributors, as well as a table of contents for the book 'Functional Python Programming.'

Uploaded by

dejvistapuro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Download Full Version ebook - Visit ebooknice.

com

(Ebook) Functional Python Programming...Efficient


Python Code by Lott S.

https://ebooknice.com/product/functional-python-programming-
efficient-python-code-56115518

Click the button below to download

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Functional Python Programming: Discover the power


of functional programming, generator functions, lazy
evaluation, the built-in itertools library, and monads by
Steven F. Lott ISBN 9781788627061, 1788627067
https://ebooknice.com/product/functional-python-programming-discover-
the-power-of-functional-programming-generator-functions-lazy-
evaluation-the-built-in-itertools-library-and-monads-7350720
ebooknice.com

(Ebook) Function Python programming: discover the power of


functional programming, generator functions, lazy
evaluation, the built-in itertools library, and monads by
Lott, Steven F ISBN 9781788621854, 1788621859
https://ebooknice.com/product/function-python-programming-discover-
the-power-of-functional-programming-generator-functions-lazy-
evaluation-the-built-in-itertools-library-and-monads-11860804
ebooknice.com

(Ebook) Clean Code in Python: Develop maintainable and


efficient code, 2nd Edition by Anaya, Mariano ISBN
9781800560215, 1800560214
https://ebooknice.com/product/clean-code-in-python-develop-
maintainable-and-efficient-code-2nd-edition-57054248

ebooknice.com

(Ebook) Learn Python Programming: A beginner's guide to


learning the fundamentals of Python language to write
efficient, high-quality code by Romano, Fabrizio ISBN
9781786468161, 9781788294874, 9781788996662,
https://ebooknice.com/product/learn-python-programming-a-beginner-s-
9782118716141, 9782507622992, 1786468166, 1788294874,
guide-to-learning-the-fundamentals-of-python-language-to-write-
efficient-high-quality-code-22092146
1788996666, 2118716141
ebooknice.com
(Ebook) Optimizing Visual Studio Code for Python
Development: Developing More Efficient and Effective
Programs in Python by Sufyan bin Uzayr ISBN 9781484273432,
1484273435
https://ebooknice.com/product/optimizing-visual-studio-code-for-
python-development-developing-more-efficient-and-effective-programs-
in-python-34775482
ebooknice.com

(Ebook) Functional programming in Python by David Mertz


ISBN 9781491928561, 1491928565

https://ebooknice.com/product/functional-programming-in-python-5852820

ebooknice.com

(Ebook) Learn to Code by Solving Problems: A Python


Programming Primer by Daniel Zingaro ISBN 9781718501324,
1718501323
https://ebooknice.com/product/learn-to-code-by-solving-problems-a-
python-programming-primer-42973688

ebooknice.com

(Ebook) C and Python Applications: Embedding Python Code


in C Programs, SQL Methods, and Python Sockets by Philip
Joyce ISBN 9781484277737, 1484277732
https://ebooknice.com/product/c-and-python-applications-embedding-
python-code-in-c-programs-sql-methods-and-python-sockets-36380876

ebooknice.com

(Ebook) Python for Secret Agents - Volume II by Lott,


Steven ISBN 9781785283406, 9781785285431, 1785283405,
1785285432
https://ebooknice.com/product/python-for-secret-agents-volume-
ii-11860802

ebooknice.com
Functional Python
Programming
Third Edition

Use a functional approach to write succinct,


expressive, and efficient Python code

Steven F. Lott

BIRMINGHAM—MUMBAI
“Python” and the Python logo are trademarks of the Python Software Foundation.
Functional Python Programming
Third Edition
Copyright © 2022 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means, without the prior written permission of the publisher,
except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information
presented. However, the information contained in this book is sold without warranty, either express
or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held
liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and
products mentioned in this book by the appropriate use of capitals. However, Packt Publishing
cannot guarantee the accuracy of this information.

Senior Publishing Product Manager: Denim Pinto


Acquisition Editor – Peer Reviews: Gaurav Gavas
Project Editor: Parvathy Nair
Development Editor: Lucy Wan
Copy Editor: Safis Editing
Technical Editor: Karan Sonawane
Indexer: Hemangini Bari
Proofreader: Safis Editing
Presentation Designer: Sandip Tadge

First published: January 2015


Second edition: April 2018
Third edition: December 2022

Production reference: 1221222


Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80323-257-7
www.packt.com
Foreword

Python is an incredibly versatile language that offers a lot of perks for just about every
group. For the object-oriented programming fans, it has classes and inheritance. When
we talk about functional programming, it has functions as a first-class type, higher-order
functions such as map and reduce, and a handy syntax for comprehensions and generators.
Perhaps best of all, it doesn’t force any of those on the user – it’s still totally OK to write a
script in Python without a single class or function and not feel guilty about it.

Thinking in terms of functional programming, having in mind the goals of minimizing state
and side effects, writing pure functions, reducing intermediary data, and what depends on
what else will also allow you to see your code under a new light. It’ll also allow you to
write more compact, performant, testable, and maintainable code, where instead of writing
a program to solve your problem, you “write the language up”, adding new functions to
it until expressing the solution you designed is simple and straightforward. This is an
extremely powerful mind shift – and an exercise worth doing. It’s a bit like learning a
new language, such as Lisp or Forth (or German, or Irish), but without having to leave the
comfort of your Python environment.

Not being a pure functional language has its costs, however. Python lacks many features
functional languages can use to provide better memory efficiency and speed. Python’s
strongest point remains its accessibility – you can fire up your Python interpreter and
start playing with the examples in this book right away. This interactive approach allows
exploratory programming, where you test ideas easily, and only later need to incorporate
them into a more complex program (or not – like I said, it’s totally OK to write a simple
script).

This book is intended for people already familiar with Python. You don’t need to know
much about functional programming – the book will guide you through many common
approaches, techniques, and patterns used in functional programming and how they can
be best expressed in Python. Think of this book as an introduction – it’ll give you the basic
tools to see, think, and express your ideas in functional terms using Python.

Ricardo Bánffy

Software Engineer, Architect, Evangelist, and Passionate Pythonista


Contributors

About the author


Steven F. Lott has been programming since computers were large, expensive, and rare.
Working for decades in high tech has given him exposure to a lot of ideas and techniques;
some are bad, but most are useful and helpful to others.

Steven has been working with Python since the ‘90s, building a variety of tools and
applications. He’s written a number of titles for Packt Publishing, include Mastering
Object-Oriented Python, Modern Python Cookbook, and Functional Python Programming.

He’s a technomad, and lives on a boat that’s usually located on the east coast of the US. He
tries to live by the words, “Don’t come home until you have a story.”
About the reviewers
Alex Martelli is a Fellow of the Python Software Foundation, a winner of the Frank
Willison Memorial Award for contributions to the Python community, and a top-page
reputation hog on Stack Overflow. He spent 8 years with IBM Research, then 13 years
at Think3 Inc., followed by 4 years as a consultant, and lately 17 years at Google. He
has taught programming languages, development methods, and numerical computing at
Ferrara University and other venues.

Books he has authored or co-authored include two editions of Python Cookbook, four
editions of Python in a Nutshell, and a chapter in Beautiful Teams. Dozens of his interviews
and tech talks at conferences are available on YouTube. Alex’s proudest achievement are
the articles that appeared in Bridge World (January and February 2000), which were hailed
as giant steps towards solving issues that had haunted contract bridge theoreticians for
decades, and still get quoted in current bridge-theoretical literature.

Tiago Antao has a BEng in Informatics and a PhD in Life Sciences. He works in the
Big Data space, analyzing very large datasets and implementing complex data processing
algorithms. He leverages Python with all its libraries to carry out scientific computing and
data engineering tasks. He also uses low-level programming languages like C, C++, and
Rust to optimize critical parts of algorithms. Tiago develops on an infrastructure based on
AWS, but has used on-premises computing and scientific clusters for most of his career.

While he currently works in industry, he also has exposure to the academic side of scientific
computing, with two data analysis postdocs at the universities of Cambridge and Oxford,
and a research scientist position at the University of Montana, where he set up, from
scratch, the scientific computing infrastructure for the analysis of biological data.

He is one of the co-authors of Biopython, a major bioinformatics package written in Python.


He wrote Bioinformatics with Python Cookbook, which is on its third edition. He has also
authored and co-authored many high-impact scientific articles in the field of bioinformatics.
Join our community Discord space
Join our Python Discord workspace to discuss and know more about the book:
https://packt.link/dHrHU
Table of Contents

Preface xxi

Chapter 1: Understanding Functional Programming 1

The functional style of programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3


Comparing and contrasting procedural and functional styles . . . . . . . . . . . . . . . . . . . . . 4
Using the functional paradigm • 5
Using a functional hybrid • 8
The stack of turtles • 9
A classic example of functional programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Exploratory data analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Convert an imperative algorithm to functional code • 18
Convert step-wise computation to functional code • 18
Revise the sqrt() function • 20
Data cleansing steps • 20
(Advanced) Optimize this functional code • 23

Chapter 2: Introducing Essential Functional Concepts 25

Functions as first-class objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26


Pure functions • 27
Higher-order functions • 29
Immutable data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Strict and non-strict evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Lazy and eager evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Recursion instead of an explicit loop state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Functional type systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Familiar territory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Learning some advanced concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Apply map() to a sequence of values • 44
Function vs. lambda design question • 45
Optimize a recursion • 45

Chapter 3: Functions, Iterators, and Generators 47

Writing pure functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48


Functions as first-class objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Using strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Using tuples and named tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Using generator expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Exploring the limitations of generators • 63
Combining generator expressions • 65
Cleaning raw data with generator functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Applying generators to built-in collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Generators for lists, dicts, and sets • 69
Using stateful mappings • 73
Using the bisect module to create a mapping • 76
Using stateful sets • 78
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Rewrite the some_function() function • 79
Alternative Mersenne class definition • 80
Alternative algorithm implementations • 81
Map and filter • 82
Dictionary comprehension • 82
Raw data cleanup • 82

Chapter 4: Working with Collections 85

An overview of function varieties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86


Working with iterables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Parsing an XML file • 89
Parsing a file at a higher level • 92
Pairing up items from a sequence • 95
Using the iter() function explicitly • 98
Extending an iteration • 100
Applying generator expressions to scalar functions • 104
Using any() and all() as reductions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Using len() and sum() on collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Using sums and counts for statistics • 111
Using zip() to structure and flatten sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Unzipping a zipped sequence • 117
Flattening sequences • 118
Structuring flat sequences • 120
Structuring flat sequences – an alternative approach • 124
Using sorted() and reversed() to change the order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Using enumerate() to include a sequence number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Palindromic numbers • 129
Hands of cards • 130
Replace legs() with pairwise() • 131
Expand legs() to include processing • 132

Chapter 5: Higher-Order Functions 133

Using max() and min() to find extrema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134


Using Python lambda forms • 138
Lambdas and the lambda calculus • 140
Using the map() function to apply a function to a collection . . . . . . . . . . . . . . . . . . . . . . 141
Working with lambda forms and map() • 143
Using map() with multiple sequences • 144
Using the filter() function to pass or reject data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Using filter() to identify outliers • 149
The iter() function with a sentinel value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Using sorted() to put data in order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Overview of writing higher-order functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Writing higher-order mappings and filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Unwrapping data while mapping • 156
Wrapping additional data while mapping • 159
Flattening data while mapping • 161
Structuring data while filtering • 164
Building higher-order functions with callables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Assuring good functional design • 168
Review of some design patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Classification of state • 173
Classification of state, Part II • 174
Optimizing a file parser • 175
Chapter 6: Recursions and Reductions 177

Simple numerical recursions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178


Implementing manual tail-call optimization • 180
Leaving recursion in place • 181
Handling difficult tail-call optimization • 182
Processing collections through recursion • 184
Tail-call optimization for collections • 185
Using the assignment (sometimes called the “walrus”) operator in recursions • 187
Reductions and folding a collection from many items to one . . . . . . . . . . . . . . . . . . . . . . 188
Tail-call optimization using deques • 190
Group-by reduction from many items to fewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Building a mapping with Counter • 195
Building a mapping by sorting • 196
Grouping or partitioning data by key values • 198
Writing more general group-by reductions • 203
Writing higher-order reductions • 205
Writing file parsers • 207
Parsing CSV files • 211
Parsing plain text files with headers • 214
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Multiple recursion and caching • 219
Refactor the all_print() function • 219
Parsing CSV files • 219
Classification of state, Part III • 220
Diesel engine data • 220

Chapter 7: Complex Stateless Objects 223

Using tuples to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224


Using NamedTuple to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Using frozen dataclasses to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Complicated object initialization and property computations . . . . . . . . . . . . . . . . . . . . . 237
Using pyrsistent to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Avoiding stateful classes by using families of tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
Computing Spearman’s rank-order correlation • 252
Polymorphism and type pattern matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Frozen dictionaries • 263
Dictionary-like sequences • 264
Revise the rank_xy() function to use native types • 265
Revise the rank_corr() function • 265
Revise the legs() function to use pyrsistent • 265

Chapter 8: The Itertools Module 267

Working with the infinite iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269


Counting with count() • 269
Counting with float arguments • 271
Re-iterating a cycle with cycle() • 275
Using cycle() for data sampling • 276
Repeating a single value with repeat() • 278
Using the finite iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Assigning numbers with enumerate() • 281
Running totals with accumulate() • 284
Combining iterators with chain() • 286
Partitioning an iterator with groupby() • 287
Merging iterables with zip_longest() and zip() • 290
Creating pairs with pairwise()) • 290
Filtering with compress() • 291
Picking subsets with islice() • 293
Stateful filtering with dropwhile() and takewhile() • 295
Two approaches to filtering with filterfalse() and filter() • 297
Applying a function to data via starmap() and map() • 298
Cloning iterators with tee() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
The itertools recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Optimize the find_first() function • 306
Compare Chapter 4 with the itertools.pairwise() recipe • 306
Compare Chapter 4 with itertools.tee() recipe • 307
Splitting a dataset for training and testing purposes • 307
Rank ordering • 307

Chapter 9: Itertools for Combinatorics – Permutations and Combina-


tions 309

Enumerating the Cartesian product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310


Reducing a product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Computing distances • 314
Getting all pixels and all colors • 318
Performance improvements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
Rearranging the problem • 323
Combining two transformations • 324
Permuting a collection of values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
Generating all combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Combinations with replacement • 333
Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Alternative distance computations • 336
Actual domain of pixel color values • 338
Cribbage hand scoring • 339

Chapter 10: The Functools Module 343

Function tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344


Memoizing previous results with cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Defining classes with total ordering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Applying partial arguments with partial() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
Reducing sets of data with the reduce() function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Combining map() and reduce() • 356
Using the reduce() and partial() functions • 358
Using the map() and reduce() functions to sanitize raw data • 360
Using the groupby() and reduce() functions • 362
Avoiding problems with reduce() • 366
Handling multiple types with singledispatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Compare string.join() and reduce() • 370
Extend the comma_fix() function • 370
Revise the clean_sum() function • 371

Chapter 11: The Toolz Package 373

The itertools star map function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374


Reducing with operator module functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
Using the toolz package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
Some itertoolz functions • 379
Some dicttoolz functions • 385
Some functoolz functions • 386
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
Replace true division with a fraction • 391
Color file parsing • 391
Anscombe’s quartet parsing • 392
Waypoint computations • 393
Waypoint geofence • 393
Callable object for the row_counter() function • 394

Chapter 12: Decorator Design Techniques 397

Decorators as higher-order functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398


Using the functools update_wrapper() function • 403
Cross-cutting concerns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
Composite design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Preprocessing bad data • 407
Adding a parameter to a decorator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Implementing more complex decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
Complicated design considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
Datetime conversions • 421
Optimize a decorator • 423
None-tolerant functions • 423
Logging • 424
Dry-run check • 425

Chapter 13: The PyMonad Library 427

Downloading and installing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428


Functional composition and currying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
Using curried higher-order functions • 431
Functional composition with PyMonad • 432
Functors – making everything a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
Using the lazy ListMonad() monad • 436
Monad bind() function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
Implementing simulation with monads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
Additional PyMonad features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
Revise the arctangent series • 449
Statistical computations • 450
Data validation • 450
Multiple models • 451

Chapter 14: The Multiprocessing, Threading, and Concurrent.Futures


Modules 453

Functional programming and concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454


What concurrency really means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
The boundary conditions • 455
Sharing resources with process or threads • 456
Where benefits will accrue • 457
Using multiprocessing pools and tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
Processing many large files • 460
Parsing log files – gathering the rows • 462
Parsing log lines into named tuples • 463
Parsing additional fields of an Access object • 467
Filtering the access details • 471
Analyzing the access details • 472
The complete analysis process • 473
Using a multiprocessing pool for concurrent processing . . . . . . . . . . . . . . . . . . . . . . . . . . 474
Using apply() to make a single request • 478
More complex multiprocessing architectures • 479
Using the concurrent.futures module • 479
Using concurrent.futures thread pools • 480
Using the threading and queue modules • 481
Using async functions • 482
Designing concurrent processing • 483
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
Lazy parsing • 487
Filter access path details • 488
Add @cache decorators • 489
Create sample data • 489
Change the pipeline structure • 490

Chapter 15: A Functional Approach to Web Services 491

The HTTP request-response model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492


Injecting state through cookies • 495
Considering a server with a functional design • 496
Looking more deeply into the functional view • 497
Nesting the services • 498
The WSGI standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
Raising exceptions during WSGI processing • 503
Pragmatic web applications • 505
Defining web services as functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
Flask application processing • 508
The data access tier • 513
Applying a filter • 515
Serializing the results • 516
Serializing data with JSON or CSV formats • 518
Serializing data with XML and HTML • 519
Tracking usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
WSGI application: welcome • 524
WSGI application: demo • 524
Serializing data with XML • 525
Serializing data with HTML • 525

Other Books You Might Enjoy 52

Index 53
Preface

Functional programming offers a variety of techniques for creating succinct and expressive
software. While Python is not a purely functional programming language, we can do a
great deal of functional programming in Python.

Python has a core set of functional programming features. This lets us borrow many design
patterns and techniques from other functional languages. These borrowed concepts can
lead us to create elegant programs. Python’s generator expressions, in particular, negate
the need to create large in-memory data structures, leading to programs that may execute
more quickly because they use fewer resources.

We can’t easily create purely functional programs in Python. Python lacks a number of
features that would be required for this. We don’t have unlimited recursion, for example,
we don’t have lazy evaluation of all expressions, and we don’t have an optimizing compiler.

There are several key features of functional programming languages that are available
in Python. One of the most important ones is the idea of functions being first-class ob-
jects. Python also offers a number of higher-order functions. The built-in map(), filter(),
and functools.reduce() functions are widely used in this role, and less obvious are
functions such as sorted(), min(), and max().

In some cases, a functional approach to a problem will also lead to extremely high-
performance algorithms. Python makes it too easy to create large intermediate data
structures, tying up memory (and processor time). With functional programming de-
sign patterns, we can often replace large lists with generator expressions that are equally
expressive but take up much less memory and run much more quickly.
xxii Preface

We’ll look at the core features of functional programming from a Python point of view.
Our objective is to borrow good ideas from functional programming languages and use
those ideas to create expressive and succinct applications in Python.

Who this book is for


This book is for more experienced programmers who want to create succinct, expressive
Python programs by borrowing techniques and design patterns from functional program-
ming languages. Some algorithms can be expressed elegantly in a functional style; we
can—and should—adapt this to make Python programs more readable and maintainable.

This is not intended as a tutorial on Python. This book assumes some familiarity with the
language and the standard library. For a foundational introduction to Python, consider
Learn Python Programming, Third Edition: https://www.packtpub.com/product/learn-p
ython-programming-third-edition/9781801815093.

While we cover the foundations of functional programming, this is not a complete review of
the various kinds of functional programming techniques. Having an exposure to functional
programming in another language can be helpful.

What this book covers


We can decompose this book into two general kinds of topics:

• Essentials of functional programming in Python. This is the content of Chapters 1


through 7.

• Library modules to help create functional programs. This is the subject of the
remaining chapters of the book. Chapter 12 includes both fundamental language and
library topics.

Chapter 1, Understanding Functional Programming, introduces some of the techniques that


characterize functional programming. We’ll identify some of the ways to map those features
to Python. We’ll also address some ways that the benefits of functional programming accrue
when we use these design patterns to build Python applications.
Preface xxiii

Chapter 2, Introducing Essential Functional Concepts, delves into central features of the
functional programming paradigm. We’ll look at each in some detail to see how they’re
implemented in Python. We’ll also point out some features of functional languages that
don’t apply well to Python. In particular, many functional languages have complex type-
matching rules required to support compiling and optimizing.

Chapter 3, Functions, Iterators, and Generators, will show how to leverage immutable Python
objects, and how generator expressions adapt functional programming concepts to the
Python language. We’ll look at some of the built-in Python collections and how we can
leverage them without departing too far from functional programming concepts.

Chapter 4, Working with Collections, shows how you can use a number of built-in Python
functions to operate on collections of data. This chapter will focus on a number of relatively
simple functions, such as any() and all(), which reduce a collection of values to a single
result.

Chapter 5, Higher-Order Functions, examines the commonly used higher-order functions


such as map() and filter(). It also shows a number of other higher-order functions as
well as how we can create our own functions that work with functions or return functions.

Chapter 6, Recursions and Reductions, teaches how to design an algorithm using recursion
and then optimize it into a high-performance for statement. We’ll also look at some other
reductions that are widely used, including collections.Counter().

Chapter 7, Complex Stateless Objects, showcases a number of ways that we can use immutable
tuples, typing.NamedTuple, and the frozen @dataclass instead of stateful objects. We’ll
also look at the pyrsistent module as a way to create immutable objects. Immutable
objects have a simpler interface than stateful objects: we never have to worry about
abusing an attribute and setting an object into some inconsistent or invalid state.

Chapter 8, The Itertools Module, examines a number of functions in the itertools standard
library module. This collection of functions simplifies writing programs that deal with
collections or generator functions.
xxiv Preface

Chapter 9, Itertools for Combinatorics – Permutations and Combinations, covers the combina-
toric functions in the itertools module. These functions are more specialized than those
in the previous chapter. This chapter includes some examples that illustrate ill-considered
use of these functions and the consequences of combinatoric explosion.

Chapter 10, The Functools Module, focuses on how to use some of the functions in the
functools module for functional programming. A few functions in this module are more
appropriate for building decorators, and they are left for Chapter 12, Decorator Design
Techniques.

Chapter 11, The Toolz Package, covers the toolz package, a number of closely related
modules that help us write functional programs in Python. The toolz modules parallel
the built-in itertools and functools modules, providing alternatives that are often more
sophisticated and make better use of curried functions.

Chapter 12, Decorator Design Techniques, covers how we can look at a decorator as a way
to build a composite function. While there is considerable flexibility here, there are also
some conceptual limitations: we’ll look at ways that overly complex decorators can become
confusing rather than helpful.

Chapter 13, The PyMonad Library, examines some of the features of the PyMonad library.
This provides some additional functional programming features. It also provides a way to
learn more about monads. In some functional languages, monads are an important way to
force a particular order for operations that might get optimized into an undesirable order.
Since Python already has strict ordering of expressions and statements, the monad feature
is more instructive than practical.

Chapter 14, The Multiprocessing, Threading, and Concurrent.Futures Modules, points out
an important consequence of good functional design: we can distribute the processing
workload. Using immutable objects means that we can’t corrupt an object because of poorly
synchronized write operations.

Chapter 15, A Functional Approach to Web Services, shows how we can think of web services
as a nested collection of functions that transform a request into a reply. We’ll see ways to
Preface xxv

leverage functional programming concepts for building responsive, dynamic web content.

Chapter 16, A Chi-Squared Case Study, is a bonus, online-only case study applying a number
of functional programming techniques to a specific exploratory data analysis problem. We
will apply a 𝜒 2 statistical test to some complex data to see if the results show ordinary
variability, or if they are an indication of something that requires deeper analysis. You can
find the case study here: https://github.com/PacktPublishing/Functional-Python-P
rogramming-3rd-Edition/blob/main/Bonus_Content/Chapter_16.pdf.

To get the most out of this book


This book presumes some familiarity with Python 3 and general concepts of application
development. We won’t look deeply at subtle or complex features of Python; we’ll avoid
much consideration of the internals of the language.

Some of the examples use exploratory data analysis (EDA) as a problem domain to show
the value of functional programming. Some familiarity with basic probability and statistics
will help with this. There are only a few examples that move into more serious data science.

Python 3.10 is required. The examples have also been tested with Python 3.11, and work
correctly. For data science purposes, it’s often helpful to start with the conda tool to create
and manage virtual environments. It’s not required, however, and readers should be able
to use any available Python.

Additional packages are generally installed with pip. The command looks like this:

% python -m pip install toolz pymonad pyrsistent beautifulsoup4

Complete the exercises


Each chapter includes a number of exercises that help the reader apply the concepts in the
chapter to real code. Most of the exercises are based on code available from the book’s
repository on GitHub: https://github.com/PacktPublishing/Functional-Python-Pro
gramming-3rd-Edition.
xxvi Preface

In some cases, the reader will notice that the code provided on GitHub includes partial
solutions to some of the exercises. These serve as hints, allowing the reader to explore
alternative solutions.

In many cases, exercises will need unit test cases to confirm they actually solve the problem.
These are often identical to the unit test cases already provided in the GitHub repository.
The reader should replace the book’s example function name with their own solution to
confirm that it works.

In some cases, the exercises suggest writing a response document to compare and contrast
multiple solutions. It helps to find a mentor or expert who can help the reader by reviewing
these small documents for clarity and completeness. A good comparison between design
approaches will include performance measurements using the timeit module to show the
performance advantages of one design over another.

Download the example code files


The code bundle for the book is hosted on GitHub at https://github.com/PacktPublis
hing/Functional-Python-Programming-3rd-Edition. We also have other code bundles
from our rich catalog of books and videos available at https://github.com/PacktPublis
hing/. Check them out!

Download the color images


We also provide a PDF file that has color images of the screenshots/diagrams used in this
book. You can download it here: https://packt.link/OV1CB.

Conventions used
There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in the text, database table names, folder names, filenames,
file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example:
“Python has other statements, such as global or nonlocal, which modify the rules for
variables in a particular namespace.”
Preface xxvii

Bold: Indicates a new term, an important word, or words you see on the screen, such as in
menus or dialog boxes. For example: “The base case states that the sum of a zero-length
sequence is 0. The recursive case states that the sum of a sequence is the first value plus
the sum of the rest of the sequence.”

A block of code is set as follows:

print("Hello, World!")

Any command-line input or output is written as follows:

% conda create -n functional3 python=3.10

Warnings or important notes appear like this.

Tips and tricks appear like this.

Get in touch
Feedback from our readers is always welcome.

General feedback: Email feedback@packtpub.com, and mention the book’s title in the
subject of your message. If you have questions about any aspect of this book, please email
us at questions@packtpub.com.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you have found a mistake in this book we would be grateful if you would
report this to us. Please visit https://subscription.packtpub.com/help, click on the
Submit Errata button, search for your book, and enter the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet,
xxviii Preface

we would be grateful if you would provide us with the location address or website name.
Please contact us at copyright@packtpub.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have ex-
pertise in and you are interested in either writing or contributing to a book, please visit
http://authors.packtpub.com.

Share your thoughts


Once you’ve read Functional Python Programming, Third Edition, we’d love to hear your
thoughts! Scan the QR code below to go straight to the Amazon review page for this book
and share your feedback.

https://packt.link/r/1803232579

Your review is important to us and the tech community and will help us make sure we’re
delivering excellent quality content.
Random documents with unrelated
content Scribd suggests to you:
fait peindre, sur la devanture de sa boutique de la rue Saint-Jacques, nº 121,
deux vers grecs, que Balzac n’a pas cités, et deux vers latins, qui ne prouvent
pas que le patron, M. Chatelet, avait fait ses humanités:

Hic fingit solers hodierno more capillos,


Dexteraque manu novos addit ars honores.

Ce qui a la prétention de vouloir dire: «Ici un art ingénieux façonne les


cheveux à la mode du jour, et d’une main habile y ajoute de nouveaux
agréments.» Cet affreux latin était mis là pour justifier l’enseigne: Au savant
Perruquier; l’une et l’autre inscription, la grecque et la latine, se voyaient
encore vers 1840. Deux autres coiffeurs avaient fait aussi un touchant appel,
en vers, aux dames et aux messieurs. Lambert, qui s’intitulait perruquier-
coiffeur, rue Notre-Dame-de-Nazareth, nº 28, était certainement l’auteur de
ce double distique, écrit des deux côtés de sa boutique; ici, côté des hommes:

Vous satisfaire est ma loi,


Pour vous attirer chez moi.

Là, de l’autre côté, côté des dames:


Aux dames, par mon talent,
Je veux être un aimant.

«C’est une chose convenue, dit Balzac, qu’en fait de poésie il n’y a que
les coiffeurs, et nous n’hésitons pas à dire qu’en fait de vers M. Lacroix a
mis le sceau à la réputation du corps.» Lacroix, perruquier-coiffeur, rue
Basse, Porte Saint-Denis, nº 8, avait mis ce quatrain au bas de son tableau
d’enseigne représentant Absalon pendu par les cheveux aux branches d’un
arbre:

Passans, contemplez la douleur


D’Absalon pendu par la nuque.
Il eût évité ce malheur,
S’il eût porté perruque.

Balzac a oublié un coiffeur de ce temps-là, Michalon, père du peintre de


ce nom, demeurant alors rue Feydeau et faisant des vers enragés de coiffeur,
qu’il exposait en tableaux à tous les coins de ses salons de coiffure.
Le Petit Dictionnaire des Enseignes de Paris cite trois magasins de
nouveautés (non pas des livres, mais des chiffons), avec des enseignes en
vers:
Primo: Au Nœud gordien, Palais-Royal, galerie de pierre, nº 233:

Du nœud gordien vous connaissez l’histoire:


Un conquérant sut le trancher.
Bien plus adroit que lui, vous aurez plus de gloire,
Si vous savez le former.

C’est là ce que dit la demoiselle de magasin, peinte sur l’enseigne, à un


élégant jeune homme qui achète une cravate et qui ne répond pas en vers.
Secundo. Au Soldat cultivateur. M. Marchandon, marchand de
nouveautés, faubourg Saint-Antoine, nº 77, avait fait faire à prix réduit, dans
l’atelier du peintre Vigneron, la copie de son tableau du Soldat laboureur,
dans lequel le soldat est représenté bêchant son champ et faisant sortir de
terre des débris d’armes et d’ossements qui annoncent que l’agriculture a
repris possession d’un ancien champ de bataille. Les vers explicatifs sont
pris dans les Géorgiques de Virgile, traduites par Delille:

Un jour, le laboureur, dans ces mêmes sillons


Où dorment les débris de tant de bataillons,
Heurtant avec le soc leur antique dépouille,
Trouvera sous ses pas des dards rongés de rouille,
Entendra résonner les casques des héros,
Et d’un œil étonné contemplera leurs os.

C’était peu réjouissant pour les demoiselles du faubourg, qui allaient


acheter manchettes, cols et foulards.
Tertio. A la Pèlerine. Magasin de mercerie, rue Saint-Honoré, nº 275,
avec ces petits vers imités d’une chanson en vogue:
Allez au magasin
Faire un pèlerinage:
Une fillette sage
Sourit au pèlerin.

Enfin, Balzac avait découvert deux sages-femmes, outre la fillette sage de


la Pèlerine, lesquelles osaient appliquer chacune deux vers à leur délicate
profession. La première, qui ne se nommait pas sur son enseigne, demeurait
rue Jean-Jacques-Rousseau, nº 23: cette enseigne représentait une belle
accouchée et son accoucheuse très élégante et fort jeune; puis, le papa tout
fier de sa progéniture, et le petit frère caressant le nouveau-né. La morale de
cette scène intime est exprimée dans ces deux vers inscrits en tête du
tableau:

Grâce à l’art, ô mon fils, enfin tu vois le jour;


Nos vœux sont exaucés, je dois bénir l’amour.

Chez la seconde sage-femme, Mᵐᵉ Vachée, rue de Buci, nº 2, on restait


interdit devant une enseigne dont la description ne saurait être plus complète
qu’elle l’est dans le Petit Dictionnaire de Balzac: «Cette dame, dit-il, voit
s’échapper d’une machine qu’on ne peut mieux comparer qu’à un four, une
nuée d’enfants habillés des costumes de différents états, et elle leur adresse
ces vers:

Sortez, mes chers enfants, et d’une ardeur commune,


Par des chemins divers, courez à la Fortune.

«Dans le lointain, la déesse elle-même, un pied sur une roue, emblème de


sa mobilité, semble inviter à la suivre la foule des jeunes mortels auxquels
Mᵐᵉ Vachée vient de donner la lumière. Mais des juifs, des usuriers, des
nymphes folâtres les séparent.» Nous avons donné plus haut (p. 292), le
dessin à peu près semblable, d’une autre enseigne de sage-femme.
Une des dernières enseignes en vers qu’on ait vues à Paris était celle d’un
tailleur, au coin de la rue d’Ulm et de la rue des Postes; mais nous ne savons
pas si le peintre était venu en aide à la poésie, car nous n’en connaissons que
ce quatrain, qui vaut tout un poème:
Accourez tous à l’abordage!
Je fais tous les raccommodages;
J’apporte grand soin aux coutures,
Aux accrocs, comme aux déchirures.

Nous regrettons de n’avoir pas parlé des écriteaux poétiques, qui sont de
véritables enseignes sans figures: ainsi toute la jeunesse du quartier latin a
connu ce facétieux brocanteur de la rue de l’École-de-médecine, qui, chaque
matin, apposait sur les objets hétéroclites de son commerce les plus étranges
annonces en prose et en vers; la prose était de sa façon, les vers sortaient de
la fabrique d’un poète crotté, qui ne manquait pas d’originalité et qui
trouvait les plus incroyables drôleries relatives à l’origine des marchandises
d’occasion.
Les contemporains de la révolution de 1830 se rappellent aussi les
affiches en vers que le marquis de Chabannes, pair de France, chansonnier,
journaliste et rimeur politique, improvisait tous les jours pour annoncer ses
brochures, ses chansons, ses prospectus, qu’il distribuait et vendait lui-
même, au Palais-Royal, dans sa boutique de la galerie d’Orléans, que la
police eut tant de peine à faire fermer, après avoir cent fois saisi, enlevé et
déchiré les affiches, au milieu des éclats de rire des spectateurs.
Enfin, en faisant appel à nos souvenirs personnels, nous revoyons encore,
vers 1840, rue Neuve Saint-Augustin, non loin de la place de la Bourse, une
boutique mystérieuse qui étalait au-dessus de son vitrage dépoli un grand
tableau représentant un monsieur mis à la dernière mode, prenant vivement
congé d’une dame non moins élégante. Au bas, se lisait ce distique
révélateur:

Ah! ah! Madame, il faut que je vous dise adieu.


Certain besoin pressant m’appelle en certain lieu!
XXV

ENSEIGNES RELATIVES A DES PIÈCES DE


THÉATRE

C ETTE espèce d’enseignes est tout à fait moderne, car elle ne date que de
l’époque où les grandes enseignes, peintes comme des tableaux et
quelquefois rivalisant avec eux, furent adoptées par la mode avec une
sorte de passion essentiellement parisienne. On peut fixer une date précise
pour le commencement des enseignes qui reproduisirent quelque scène de la
pièce en vogue. Ce fut seulement sous l’Empire que parurent les premiers
essais de ce genre nouveau d’enseignes, qui ont attiré presque exclusivement
l’attention des curieux de ce qu’on appela dès lors le Musée des rues. Il n’y a
que les pièces de théâtre, à grand succès, qui aient mérité la consécration de
l’enseigne. C’étaient donc, chaque année, quatre ou cinq enseignes
nouvelles, qui rappelaient au public les grands succès récents. Le type de
l’enseigne devenait ainsi populaire, et la vogue de la pièce profitait à
l’industriel qui l’avait adopté. Les enseignes théâtrales firent fureur pendant
plus de cinquante ans; elles s’étaient, pour ainsi dire, emparées de la ville
entière, et le succès d’une pièce de théâtre n’était jamais mieux constaté que
par l’apparition d’une enseigne qui en portait le nom.
On peut affirmer que l’idée de faire des enseignes de ce genre n’était
jamais venue à l’esprit des marchands avant le Directoire; du moins n’en
connaissons-nous qu’une seule, l’enseigne du Huron, consacrant, en 1769, le
succès d’un opéra-comique de Grétry, et dont nous parlerons plus loin, au
chapitre XXIX. Les succès les plus extraordinaires, comme celui de Jeannot,
ou les Battus paient l’amende, le proverbe-comédie-parade de Dorvigny,
représenté trois cents fois de suite chez Nicolet, ou comme celui du Mariage
de Figaro, qui fit autant de bruit qu’une révolution, ces succès ne donnèrent
pas lieu à la création d’une seule enseigne. Le moment n’était pas venu,
quoique depuis 1761 les enseignes, appliquées contre le mur des maisons, au
lieu d’être suspendues à des potences en fer dans des cadres mobiles, se
prêtassent mieux à l’exposition de tableaux. On comprend que le goût du
spectacle, si décidé et si général chez les habitants de Paris, se soit traduit
par cette innovation dans le système des enseignes, en un temps où le
nombre des théâtres avait triplé. Il faut dire aussi qu’avant ce temps-là les
marchands menaient une vie très retirée et très parcimonieuse, sans songer à
imiter les habitudes des autres classes de la société, qui ne se faisaient pas
faute d’aller à la comédie. Les enseignes des boutiques ne subirent
l’influence du théâtre que quand les boutiquiers commencèrent à se montrer
et à s’acclimater dans les salles de spectacle.
Nous trouvons cependant que les ballets de cour eurent, dans la première
moitié du XVIIᵉ siècle, certaines analogies avec plusieurs enseignes de Paris.
Ainsi l’enseigne primitive du Cherche-Midi, qui a précédé celle dont nous
avons parlé plus haut, page 84, était sans doute bien antérieure au ballet des
Chercheurs de midi à quatorze heures, ballet qui fut dansé, au Louvre, en
présence du roi, le 29 janvier 1620. Ce ballet[260], que nous ne connaissons
que par un petit programme en vers très libres, a peu de rapport avec
l’enseigne qui représentait des gens de diverses conditions, cherchant l’heure
de midi sur un cadran dont les aiguilles marquaient quatorze heures, comme
dans les horloges d’Italie. Les chercheurs de midi à quatorze heures, qu’on
appelait des cherche-midi, étaient de pauvres hères faméliques en quête du
dîner, qu’ils ne trouvaient pas à quatorze heures, car on dînait partout à midi.
Un roman picaresque d’Oudin, sieur de Préfontaine[261], nous apprend le
véritable rôle d’un cherche-midi, que le ballet mit en scène sous les traits du
joueur de gobelets, du batteur de fusil, du ramoneur, du vendeur de lunettes:
«La grande nécessité où j’estois m’ayant pourveu d’un office de cherche-
midy, j’allois parfois en des couvents, mais j’y trouvois petite chance, au
moins pour moy, car, pour les moynes, ils faisoient une telle chère, que, si la
fumée de leurs bons morceaux qui me passoient devant le nez avoit esté
rassasiante, cela m’auroit bien nourry.» Un autre ballet de cour, qui a pour
titre la Fontaine de Jouvence[262], imprimé en 1643 et par conséquent dansé
cette année-là au château de Saint-Germain, pourrait bien avoir été inspiré
par la jolie enseigne du XVIᵉ siècle dont nous avons parlé et qui attirait tous
les regards dans la rue du Four-Saint-Germain. Enfin, dans un ballet du roi, à
la naissance du Dauphin, en 1643, les Enseignes de Paris faisaient leur
entrée sous la figure d’une femme qui se plaignait des dégâts que les grands
vents lui avaient causés dans les derniers orages. Voici deux strophes que
Dassoucy avait mises dans la bouche de cette fée des enseignes[263]:
Je suis cette aimable Syrène,
Qui, des orages précédents,
Vient faire une plainte à la Reyne,
Contre l’insolence des vents,
Afin que leur Dieu se retire,
Et qu’il trouble les flots plutôt que mon empire:
Ce monstre, plein d’insolence,
A causé, par nostre débris,
Que l’on trouve plus d’assurance
A Saint-Germain qu’à Paris.
Aussi, pour éviter sa rage,
Nous nous rendons ici à l’abry de l’orage.

A partir de là, comme si toutes les enseignes de Paris avaient été


décrochées et brisées par l’ouragan, elles ne reparaissent plus au théâtre que
dans deux chétifs vaudevilles: l’un, de Martainville: Pataquès, ou le
Barbouilleur d’enseignes, joué en 1803; l’autre, de Brazier, Moreau et La
Fortelle, Tout pour l’enseigne, représenté le 18 avril 1815. Ces deux petites
pièces ne réussirent pas. C’est que les marchands et leurs commis ne
souffraient pas qu’on se gaussât de leurs enseignes. Scribe et Saint-Georges
l’apprirent à leurs dépens, quand leur opéra-comique, en trois actes, le Fidèle
Berger, dont Adolphe Adam avait fait la musique, fut outrageusement sifflé,
à la première représentation, le 11 janvier 1838. Les auteurs n’avaient pas
trop ménagé la confiserie parisienne, mise en scène sous la bannière de la
vieille enseigne du Fidèle Berger: on se battit au parterre, et les perturbateurs
qui furent arrêtés étaient tous des confiseurs: «Ces gaillards-là, dit Scribe,
seraient capables de m’empoisonner avec leurs dragées de baptême.» Il ne fit
pas imprimer sa pièce, qui n’a paru que dans la dernière édition de ses
Œuvres complètes; le musicien essaya de la faire jouer à Bruxelles, où elle
fut traitée en douceur[264]. Les confiseurs du Fidèle Berger n’étaient plus là.
Marchands à enseignes et auteurs dramatiques furent depuis en parfaite
intelligence, lorsque les enseignes des premiers contribuèrent grandement à
la renommée des seconds.
Il est impossible d’entrer ici dans quelques détails sur les pièces de
théâtre auxquelles on accorda les honneurs de l’enseigne depuis cinquante
ou soixante ans; nous nous bornerons donc à citer, d’après le Petit
Dictionnaire critique et anecdotique des Enseignes de Paris, celles de ces
enseignes inaugurées sous les titres mêmes des pièces de différents genres,
aux succès desquelles les marchands avaient attaché celui de leur commerce.
Il suffit de rappeler que ces pièces étaient encore très connues en 1826, bien
que quelques-unes remontassent aux premières années de l’Empire;
plusieurs, d’une date plus ancienne, comme le Diable à quatre de Sedaine,
les Trois Sultanes de Favart, et la Partie de chasse de Henri IV, par Collé,
avaient été reprises avec éclat et étaient restées au répertoire.
Les tableaux dont on faisait des enseignes furent souvent composés et
exécutés par de véritables peintres. Nous parlerons, dans le chapitre XXIX,
Musée des enseignes, de ceux qui sortaient de l’atelier des meilleurs artistes.
L’Académie royale de musique reconnaissait des opéras et des ballets de
son répertoire dans les enseignes suivantes: Aux Bayadères, boulevard des
Italiens, nº 9, Nouveautés. Les Bayadères, opéra en trois actes, paroles de
Jouy, musique de Catel, représenté le 8 août 1810.—A la Vestale, rue
Montmartre, au coin de la rue de Cléry, Nouveautés. La Vestale, tragédie
lyrique de Jouy, musique de Spontini, fut représentée le 11 décembre 1807.
—A la Lampe merveilleuse, Demarais, lampiste, illuminateur du
Gouvernement. Aladin, ou la Lampe merveilleuse, opéra-féerie en cinq
actes, par Étienne, musique de Nicolo et de Benincori, fut représenté le 6
février 1822.—Au Triomphe de Trajan, M. Payen, tailleur, rue de Richelieu,
nº 77. Le Triomphe de Trajan, tragédie lyrique en trois actes, par Esmenard,
musique de Lesueur et de Pertuis, fut représenté le 23 octobre 1807.
Passons au Théâtre-Français, qui avait vu, en plein Directoire, apparaître
l’enseigne des Trois Sultanes, un des plus beaux tableaux d’enseigne de
Paris, pour annoncer le magasin de mesdames Delatour, lingères, rue
Vivienne, au coin de la rue Colbert.—A Marie Stuart, Nouveautés, rue Saint-
Denis, nº 392. Marie Stuart, tragédie de Pierre Lebrun, représentée en 1820.
—Aux Templiers, rue Feydeau, nº 16, Michalon, coiffeur. Les Templiers,
tragédie de Raynouard, représentée en 1805.—A la Fille d’honneur, rue de
la Monnaie, au coin de la rue Boucher. La Fille d’honneur, comédie en cinq
actes et en vers, par Alexandre Duval, représentée en 1819.—A Valérie, rue
Saint-Denis, nº 309, magasin de nouveautés. Valérie, comédie, en trois actes
et en prose, par Scribe et Melesville, représentée en 1822.—Aux Deux
Cousines, magasin de nouveautés, rue Coquillière. L’Éducation, ou les Deux
Cousines, comédie en cinq actes et en vers, par Casimir Bonjour, fut
représentée en 1824.
Le théâtre de la porte Saint-Martin avait fourni, à lui seul, deux fois plus
d’enseignes que l’Opéra et le Théâtre-Français: Au Vampire, magasin de
nouveautés, rue Saint-Antoine.—Au Bourgmestre de Saardam, Grisard,
drapier, rue Saint-Honoré, nº 53.—Aux Petites Danaïdes, Potier, confiseur,
boulevard Saint-Martin, nº 57. (Il ne faudrait pas confondre l’acteur avec le
confiseur, malgré la similitude du nom: le fameux comédien Potier avait créé
le rôle du Père Sournois, dans les Petites Danaïdes, de Gentil et de
Désaugiers.)—Au Solitaire, Malard, marchand de nouveautés, rue du
Faubourg-Saint-Denis, nº 68.—A Joko, ou le Singe du Brésil.—A Polichinel
(sic) vampire.—A la Fille mal gardée.—Aux Ramoneurs.—Au Déserteur,
etc.

Les enseignes drôlatiques se rapportaient surtout à des pièces du théâtre


des Variétés, dans lesquelles avaient figuré les premiers acteurs de ce théâtre,
Brunet, Potier, Odry, Vernet, Bouffé, etc., comme le Désespoir de Jocrisse,
le Ci-devant Jeune Homme, etc. Le théâtre du Vaudeville inspirait des sujets
d’enseignes gaies et plaisantes, sans être bouffonnes, comme les Deux
Gaspard du faubourg Saint-Denis, dont nous avons donné la figure page
197, les Deux Edmond, le Petit Matelot, Monsieur Dumolet, Monsieur
Pigeon (le héros d’Une Nuit de la Garde nationale), dans la rue de Seine,
etc. Il y avait aussi les enseignes patriotiques, ou chauvinesques, que le
Vaudeville, les Variétés, le Cirque Olympique, et même le Gymnase,
auraient dû fournir en plus grande quantité, mais que la crainte de la Censure
interdisait souvent aux commerçants les plus paisibles; nous en pourrions
néanmoins citer une vingtaine, entre autres, les Deux Sergents, dans la rue
Saint-Honoré, en face la rue du Coq, aujourd’hui Marengo; Fanfan la Tulipe,
Michel et Christine, le Soldat laboureur, le Chien du Régiment, François les
Bas-bleus, à l’angle du faubourg Montmartre et de la rue Fléchier, etc.
Presque tous les grands succès du Gymnase dramatique, dus la plupart à
l’infatigable fécondité du talent de Scribe, furent signalés par l’apparition de
nouvelles enseignes, qui augmentaient et prolongeaient la vogue de Malvina,
ou le Mariage d’inclination, du Mariage enfantin, de la Carotte d’Or, du
Gamin de Paris, du Comédien d’Étampes, etc.[265].
Les spectacles du boulevard du Temple, la Gaîté,

l’Ambigu-Comique, le Cirque Olympique, les Funambules, etc., avaient eu


aussi de grands succès populaires, et, par conséquent, ces succès s’étaient
affirmés par un grand nombre d’enseignes boutiquières, qui duraient
beaucoup plus longtemps que ces pièces de différents genres,
telles que l’Oiseau bleu, les Deux Pierrots, qui sont toujours en place, au
coin de la rue Saint-Jacques et de la rue de la Huchette (voir figure p. 349),
les Innocents, les Quatre Sergents de la Rochelle, du boulevard
Beaumarchais, etc. Mais, comme tout passe ici-bas, les plus beaux drames,
les plus merveilleuses féeries, les plus amusantes pantomimes, les
mimodrames les plus éblouissants n’avaient qu’un temps, et, après cent ou
deux cents représentations, étaient absolument oubliés, en sorte que les
enseignes nées de leur vogue pouvaient à peine leur survivre. Voilà comment
la plupart des enseignes qui rappelaient à la foule les mélodrames de
Guilbert de Pixérécourt disparurent avant le célèbre auteur de la Femme à
deux maris, de Cœlina, ou l’Enfant du Mystère, du Chien de Montargis et de
Latude.
Les pièces en musique, les opéras-comiques, dont les airs deviennent si
populaires, quand l’orgue de Barbarie les propage, multiplièrent les
enseignes peintes d’après nature, avec les portraits des plus célèbres
chanteurs et chanteuses du théâtre de l’Opéra-Comique: A la Clochette, Au
Chaperon rouge, A Joconde, A la Somnambule, A la Dame blanche, etc.
La révolution du 24 février 1848 marqua le déclin du règne de ces sortes
d’enseignes à Paris. Les marchands conservèrent celles qui avaient fait la
réputation de leurs maisons de commerce; mais il fallut bien reconnaître,
petit à petit, que les enseignes en tableaux étaient démodées; puis, certains
propriétaires trouvèrent à redire à ces enseignes, qui pouvaient parfois
diminuer la valeur d’un immeuble. On avait aussi constaté qu’une enseigne
peinte à l’huile, étant toujours exposée à l’air, subissait à son détriment les
variations de la température; on devait donc, de temps à autre, la faire
revernir ou même la soumettre à de plus sérieuses réparations. Bien d’autres
raisons achevèrent de discréditer ce genre d’enseignes. On avait pourtant
évité avec soin, malgré le succès énorme de certaines pièces de théâtre, telles
que la Vie d’un joueur, l’Auberge des Adrets, le Faussaire, Cartouche, etc.,
de donner à tel ou tel magasin une enseigne qui pouvait prêter à des allusions
ou à des rapprochements désagréables. On vit donc peu à peu disparaître les
enseignes empruntées à des pièces de théâtre, sous prétexte qu’une ancienne
pièce n’avait plus de sens aux yeux d’une génération nouvelle. La
suppression de ces enseignes, souvent fort coûteuses, gagna de proche en
proche, et le public n’eut pas l’air de s’en apercevoir. Ce fut le
commencement de la décadence de toutes les enseignes peintes. On s’était
convaincu, par expérience, que si les annonces de la quatrième page des
grands journaux politiques, inaugurées en 1837 par Emile de Girardin et
Dutacq, coûtaient plus cher que les plus belles enseignes, elles rapportaient
dix fois davantage. L’annonce et la réclame, qui détrônaient décidément
l’enseigne, finirent pourtant par avoir la leur, au nº 31 de la rue Croix-des-
Petits-Champs, où s’étale en belle place une assez pauvre figure d’une
Renommée gigantesque, en mosaïque grisaille sur fond d’or, avec cette
légende éloquente: Ars famæ[266].
Il existe encore, ainsi qu’on a pu le voir au cours de cet ouvrage, un assez
grand nombre d’anciennes enseignes peintes, mais on n’en fait plus guère de
nouvelles, bien que, devenant plus rares, on doive peut-être les remarquer
davantage. Nous n’avons pas à faire l’histoire de ces enseignes de la dernière
heure, quoique plusieurs soient encore des signes de la tradition; nous n’en
citerons qu’une, qui produisit tout l’effet de curiosité qu’on pouvait attendre
d’une enseigne: Aux Mystères de Paris, ancienne maison Bourdillot, 6, rue
du Temple, Guibert, spécialité de blanc et lingerie. Le succès des Mystères
de Paris, d’Eugène Sue, valait bien une enseigne. Il est bon de rappeler que
le Juif errant, dont le succès fut encore plus grand, avait été accueilli au
théâtre avec la même faveur que le roman parmi les lecteurs, mais pas un
marchand n’osa s’attribuer une aussi fâcheuse enseigne, sous peine d’être
montré au doigt, comme un juif dénoncé par son enseigne.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like