Python Distilled 1St Edition - Ebook PDF: or Click Button
Python Distilled 1St Edition - Ebook PDF: or Click Button
com
https://ebooksecure.com/download/python-distilled-ebook-pdf/
OR CLICK BUTTON
DOWLOAD EBOOK
http://ebooksecure.com/product/ebook-pdf-building-python-
programs-1st-edition/
http://ebooksecure.com/product/python-for-dummies-1st-edition-
pdf-version/
https://ebooksecure.com/download/problem-solving-and-python-
programming-ebook-pdf/
https://ebooksecure.com/download/programming-and-problem-solving-
with-python-ebook-pdf/
Data Structures & Algorithms in Python 1st Edition John
Canning - eBook PDF
https://ebooksecure.com/download/data-structures-algorithms-in-
python-ebook-pdf-2/
https://ebooksecure.com/download/data-structures-algorithms-in-
python-ebook-pdf/
https://ebooksecure.com/download/r-and-python-for-oceanographers-
a-practical-guide-with-applications-ebook-pdf/
http://ebooksecure.com/product/ebook-pdf-starting-out-with-
python-4th-edition/
http://ebooksecure.com/product/ebook-pdf-python-programming-in-
context-3rd-edition/
Python Distilled
This page intentionally left blank
Python Distilled
David M. Beazley
The author and publisher have taken care in the preparation of this book, but make no expressed or
implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed
for incidental or consequential damages in connection with or arising out of the use of the information or
programs contained herein.
For information about buying this title in bulk quantities, or for special sales opportunities (which may
include electronic versions; custom cover designs; and content particular to your business, training goals,
marketing focus, or branding interests), please contact our corporate sales department
at corpsales@pearsoned.com or (800) 382-3419.
For questions about sales outside the U.S., please contact intlcs@pearson.com.
All rights reserved. This publication is protected by copyright, and permission must be obtained from the
publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or
by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding
permissions, request forms and the appropriate contacts within the Pearson Education Global Rights &
Permissions Department, please visit www.pearson.com/permissions.
ISBN-13: 978-0-13-417327-6
ISBN-10: 0-13-417327-9
ScoutAutomatedPrintCode
Contents
Preface xiii
1 Python Basics 1
1.1 Running Python 1
1.2 Python Programs 2
1.3 Primitives, Variables, and
Expressions 3
1.4 Arithmetic Operators 5
1.5 Conditionals and Control Flow 7
1.6 Text Strings 9
1.7 File Input and Output 12
1.8 Lists 13
1.9 Tuples 15
1.10 Sets 17
1.11 Dictionaries 18
1.12 Iteration and Looping 21
1.13 Functions 22
1.14 Exceptions 24
1.15 Program Termination 26
1.16 Objects and Classes 26
1.17 Modules 30
1.18 Script Writing 32
1.19 Packages 33
1.20 Structuring an Application 34
1.21 Managing Third-Party Packages 35
1.22 Python: It Fits Your Brain 36
5 Functions 101
5.1 Function Definitions 101
5.2 Default Arguments 101
5.3 Variadic Arguments 102
5.4 Keyword Arguments 103
5.5 Variadic Keyword Arguments 104
5.6 Functions Accepting All Inputs 104
5.7 Positional-Only Arguments 105
5.8 Names, Documentation Strings, and Type
Hints 106
5.9 Function Application and Parameter
Passing 107
5.10 Return Values 109
5.11 Error Handling 110
5.12 Scoping Rules 111
5.13 Recursion 114
viii Contents
6 Generators 139
6.1 Generators and yield 139
6.2 Restartable Generators 142
6.3 Generator Delegation 142
6.4 Using Generators in Practice 144
6.5 Enhanced Generators and yield
Expressions 146
6.6 Applications of Enhanced
Generators 148
6.7 Generators and the Bridge to
Awaiting 151
6.8 Final Words: A Brief History of
Generators and Looking
Forward 152
Index 321
Preface
More than 20 years have passed since I authored the Python Essential Reference. At that time,
Python was a much smaller language and it came with a useful set of batteries in its
standard library. It was something that could mostly fit in your brain. The Essential Reference
reflected that era. It was a small book that you could take with you to write some Python
code on a desert island or inside a secret vault. Over the three subsequent revisions, the
Essential Reference stuck with this vision of being a compact but complete language
reference —because if you’re going to code in Python on vacation, why not use all of it?
Today, more than a decade since the publication of the last edition, the Python world is
much different. No longer a niche language, Python has become one of the most popular
programming languages in the world. Python programmers also have a wealth of
information at their fingertips in the form of advanced editors, IDEs, notebooks, web
pages, and more. In fact, there’s probably little need to consult a reference book when
almost any reference material you might want can be conjured to appear before your eyes
with the touch of a few keys.
If anything, the ease of information retrieval and the scale of the Python universe
presents a different kind of challenge. If you’re just starting to learn or need to solve a new
problem, it can be overwhelming to know where to begin. It can also be difficult to
separate the features of various tools from the core language itself. These kinds of problems
are the rationale for this book.
Python Distilled is a book about programming in Python. It’s not trying to document
everything that’s possible or has been done in Python. Its focus is on presenting a modern
yet curated (or distilled) core of the language. It has been informed by my years of teaching
Python to scientists, engineers, and software professionals. However, it’s also a product of
writing software libraries, pushing the edges of what makes Python tick, and finding out
what’s most useful.
For the most part, the book focuses on Python programming itself. This includes
abstraction techniques, program structure, data, functions, objects, modules, and so
forth— topics that will well serve programmers working on Python projects of any size.
Pure reference material that can be easily obtained via an IDE (such as lists of functions,
names of commands, arguments, etc.) is generally omitted. I’ve also made a conscious
choice to not describe the fast-changing world of Python tooling —editors, IDEs,
deployment, and related matters.
Perhaps controversially, I don’t generally focus on language features related to large-scale
software project management. Python is sometimes used for big and serious things—
comprised of millions upon millions of lines of code. Such applications require specialized
tooling, design, and features. They also involve committees, and meetings, and decisions
to be made about very important matters. All this is too much for this small book. But
xiv Preface
perhaps the honest answer is that I don’t use Python to write such applications— and
neither should you. At least not as a hobby.
In writing a book, there is always a cut-off for the ever-evolving language features. This
book was written during the era of Python 3.9. As such, it does not include some of the
major additions planned for later releases — for example, structural pattern matching.
That’s a topic for a different time and place.
Last, but not least, I think it’s important that programming remains fun. I hope that my
book will not only help you become a productive Python programmer but also capture
some of the magic that has inspired people to use Python for exploring the stars, flying
helicopters on Mars, and spraying squirrels with a water cannon in the backyard.
Acknowledgments
I’d like to thank the technical reviewers, Shawn Brown, Sophie Tabac, and Pete Fein, for
their helpful comments. I’d also like to thank my long-time editor Debra Williams Cauley
for her work on this and past projects. The many students who have taken my classes have
had a major if indirect impact on the topics covered in this book. Last, but not least, I’d
like to thank Paula, Thomas, and Lewis for their support and love.
· · · · · · · · · · · · · · · ·
· · · · · · · · · · · · · · · ·
· · · · · · · · · · · · · · · ·
Noi interrompemmo il racconto della signora Giovannina, per
esclamare con indignazione:
— Ma era una cattiva madre!
— Una donna senza cuore!
— Un’egoista!
La signora Giovannina stette zitta un lungo tratto, chiudendo quasi
gli occhi, e stringendo le labbra, come per fare violenza a sè stessa e
trattenere le parole che le venivano in bocca. Poi disse con molta
fermezza:
— No. Anch’io ho pensato come voi alla vostra età, ed ho giudicato
quella donna severamente. Ma ho fatto male. Più tardi dovetti
riconoscerlo. Fu sempre per le sue figlie una madre affettuosa, le
allevò colla massima tenerezza; guai se si ammalavano, se alla
scuola subivano qualche piccola ingiustizia; era sempre pronta ad
assisterle, a difenderle con una parzialità affatto materna. Quando
l’Editta fu colpita dall’artritide che durò più d’un anno nello stato
acuto, poi prese un carattere cronico, la mamma abbandonò ogni
cosa per curarla giorno e notte, non risparmiò nè fatiche nè veglie,
tutti la videro soffrire, agire ed amare come una vera e buona
madre.
Io risposi:
— Però deve ammettere che, quelle povere figlie, le amava molto
male, e le sacrificava. Lei non aveva diritto di disporre della loro vita.
— È vero. Ma era semplice di mente. Queste cose che tu dici non le
sapeva. Siccome il privarsi delle sue figlie era un sacrificio, un dolore
anche per lei, non poteva immaginarsi d’essere egoista. Chi non sa
di fare il male è come se non lo facesse. Credete a me, ragazze, non
abbiamo diritto noi di erigerci a giudici. Io ho compreso questo,
quando ho veduto Andrea, quel giovane buono ed onesto, troncare
ad un tratto tutte le mie speranze, il mio avvenire di donna, per una
questione di principii giusta a’ suoi occhi, ma troppo severa. Ho
compreso allora che si può far male ad altri senza essere cattivi, nè
colpevoli:
Mia sorella disse:
— Oh è stato cattivo, sì, quella volta il nonno con lei. È stato crudele.
Io non glielo posso perdonare.
E la vecchia, con un accento secco, come di stizza, rispose:
— Ed io sì. Voi siete giovani. Non sapete. Ma quando si vede che una
persona è buona, giusta, onesta in tutta la sua vita, non si deve
giudicarla per un atto solo che sembra crudele. Può essere soltanto
uno sbaglio; e può essere che noi non lo comprendiamo e che sia un
atto buono, nel fine o nell’intenzione. Il nostro cuore di donna ci
porta a stimare barbare le madri spartane, che spingevano i loro figli
in guerra, e non piangevano quando erano morti. Invece pare che
fossero migliori delle altre madri, grandi addirittura. Siamo noi
povere donnette semplici, che non le comprendiamo. Forse al mondo
non vi sono vere cattiverie; vi sono soltanto degli errori.
La signora Giovannina finì quel discorso mite, che aveva detto
coll’asprezza d’una invettiva, e rimase assorta in quelle riflessioni,
che chissà quanta parte avevano occupata nella sua povera vita
solitaria.
Io era stupita, come se la vedessi e la udissi per la prima volta.
Non avrei mai supposto che quella vecchia zitella, priva di coltura,
piena di piccole manìe, fosse capace, per sola intelligenza e nobiltà
d’animo naturali, di quelle due virtù tanto grandi e pie:
Essere indulgente, e non giudicare il prossimo.
Sono le più difficili delle virtù umane.
Il perdono, la dolce virtù del perdono, che Cristo ci comanda e ci
insegna, non è che una riparazione per chi ha mancato a queste
altre. Chi ha commesso l’atto di superbia di giudicare arbitrariamente
un suo simile, deve poi espiarlo, perdonando la colpa che gli ha
imputato.
Ma l’uomo umile e giusto, che dice: — «Io non posso giudicare le
azioni d’un altro, perchè non gli vedo nel cuore; perchè, forse, anche
facendo quanto a me sembra male, ha delle intenzioni buone», —
quel giusto, non ha bisogno di perdonare.
Queste cose che ora dico, allora le sentivo soltanto. Ed ammiravo
quella vecchia semplice e sfortunata, che in tanti lunghi anni di vita
senza gioie, non le aveva rinnegate.
La signora Giovannina dovette darsi una scrollata famosa per
riscuotersi da quelle idee filosofiche. Tutti i suoi abiti, i nastri, le gale,
svolazzarono; la panca tremò, e noi saltammo sulla panca, come se
ci fosse il terremoto.
Poi ella riprese a parlare in fretta, come per farci dimenticare quegli
sfoghi di sentimento e quei voli di pensiero, dei quali, nella sua
timidezza selvatica, si vergognava.
· · · · · · · · · · · · · · · ·
«Caro Andrea,
«Io accetto, per obbedienza figliale una vita di sacrificio.
Accettatela anche voi per sentimento di carità. Sposate la mia
povera Editta; toglietela a quell’esistenza tribolata, a quei
maltrattamenti che la uccidono.»
«È la sola prova che posso domandarvi del vostro amore, e ve
ne sarò grata, e vi benedirò per tutta la vita, e pregherò per
voi.»
«Delfina.»