Download Complete (Ebook) Functional Python Programming...Efficient Python Code by Lott S. PDF for All Chapters
Download Complete (Ebook) Functional Python Programming...Efficient Python Code by Lott S. PDF for All Chapters
com
https://ebooknice.com/product/functional-python-programming-
efficient-python-code-56115518
DOWLOAD EBOOK
ebooknice.com
https://ebooknice.com/product/functional-programming-in-python-5852820
ebooknice.com
ebooknice.com
ebooknice.com
ebooknice.com
Functional Python
Programming
Third Edition
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.
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
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.
Preface xxi
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.
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.
• 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 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 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.
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:
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.
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.”
print("Hello, World!")
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.
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:
«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:
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:
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.
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.
ebooknice.com