Fluent Python Luciano Ramalho download
Fluent Python Luciano Ramalho download
https://ebookmeta.com/product/fluent-python-luciano-ramalho/
Luciano Ramalho
Fluent Python
by Luciano Ramalho
First Edition
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo
are registered trademarks of O’Reilly Media, Inc. !!FILL THIS IN!! and
related trade dress are trademarks of O’Reilly Media, Inc.
[?]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . xv
Part I. Prologue
String representation 11
Arithmetic operators 11
Chapter summary 14
Further reading 15
Cartesian products 23
Generator expressions 25
Tuples as records 26
Tuple unpacking 27
Named tuples 30
Slicing 33
Slice objects 34
Assigning to slices 36
Using + and * with sequences 36
A += assignment puzzler 40
Arrays 48
Memory views 51
Chapter summary 57
Further reading 58
dict comprehensions 66
Variations of dict 75
Subclassing UserDict. 76
Immutable mappings 77
Set theory 79
set literals 80
set comprehensions 81
Set operations 82
A performance experiment 85
vi | Table of Contents
Chapter summary 93
Further reading 94
4. Text versus bytes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . 97
Character issues 98
Byte essentials 99
5. First-class functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . 139
Command 177
9. A Pythonic object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . 247
Table of Contents | ix
x | Table of Contents
13. Operator overloading: doing it right. . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . 373
16. Coroutines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . 465
Afterword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . 685
A. Support scripts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . 689
Python jargon. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . 717
Preface
Here’s the plan: when someone uses a feature you don’t understand,
simply shoot them.
This is easier than learning something new, and before too long the
only living coders
— Tim Peters
writing Python code with a very strong accent carried from languages
learned before.
another problem that this book tries to address: we only miss stuff
we know about.
pressions, and look that up in the docs. But if you’ve never seen tuple
unpacking or
descriptors before, you will probably not search for them, and may
end up not using
those features just because they are specific to Python.
features that are either unique to Python or not found in many other
popular languages.
This is also mostly a book about the core language and some of its
libraries. I will rarely
talk about packages that are not in the standard library, even though
the Python package
index now lists more than 53.000 libraries and many of them are
incredibly useful.
xv
XXXtodo
This book was written for practicing Python programmers who want
to become pro‐
the fixes needed to make the code work in earlier versions. Most
examples should run
significant rewriting.
Having said that, I believe this book may be useful even if you must
stick with Python
2.7, because the core concepts are still the same. Python 3 is not a
new language, and
starting point. Of course, there have been changes after Python 3.0
was released in 2009,
If you are not sure whether you know enough Python to follow along,
review the topics
of the official Python Tutorial. Topics covered in the tutorial will not
be explained here, except for some features that are new in Python
3.
The core audience for this book should not have trouble jumping
directly to any chapter
in this book. However, I did put some thought into their ordering.
xvi | Preface
inherit from existing ABCs than to create a new ABC from scratch.
And finally, I believe
chapters. I hope these will be easier to tolerate now that you know
why I chose this path.
The chapters are split in 6 parts. This is the idea behind each of
them:
Part I: Prologue
A single chapter about the Python Data Model explaining how the
special methods
data model is the subject of most of the rest of the book, but Chapter
1 provides a high-level overview.
sets, as well as the str versus bytes split — the reason for much joy
for Python 3
users and much pain for Python 2 users who have not yet migrated
their code bases.
The main goals are to recall what is already available and to explain
some behavior
goals, the coverage is sometimes high level and wide — when many
variations of
we dive into the hash tables underneath the dict and set types.
collections and ABCs, how to cope with multiple inheritance and how
to implement
Preface | xvii
Covered in this part are the language constructs and libraries that go
beyond se‐
powerful new yield from syntax. Part V closes with high level a
introduction to
processes under the covers with the help of futures — and doing
event-oriented I/
This part starts with a review of techniques for building classes with
attributes
the use of the advanced tools of the last chapter: class decorators
and metaclasses.
Hands-on Approach
a REPL — read-eval-print-loop.
doctest to check most of the code in this book, including the console
listings. You don’t
need to use or even know about doctest to follow along: the key
feature of doctests is
how to do it helps focus our coding effort. Writing tests first is the
basis of TDD (Test
Driven Development) and I’ve also found it helpful when teaching. If
you are unfamiliar
with doctest, take a look at its documentation and this book’s source
code repository.
You’ll find that you can verify the correctness of most of the code in
the book by typing
xviii | Preface
The book has some simple benchmarks and timings. Those tests
were performed on
one or the other laptop I used to write the book: a 2011 MacBook
Pro 13” with a 2.7
GHz Intel Core i7 CPU, 8MB of RAM and a spinning hard disk, and a
2014 MacBook
Air 13” with a 1.4 GHZ Intel Core i5 CPU, 4MB of RAM and a solid
state disk. The
MacBook Air has a slower CPU and less RAM, but its RAM is faster
(1600 vs. 1333
MHz) and the SSD is much faster than the HD. In daily usage I can’t
tell which machine
is faster.
about Python and other languages. Feel free to skip that if you are
not into such dis‐
Python Jargon
I wanted this to be a book not only about Python but also about the
culture around it.
own particular lingo and acronyms. The Python jargon collects terms
that have special meaning among Pythonistas.
I tested all the code in the book using Python 3.4 — that is, CPython
3.4, i.e. the most
“The new @ infix operator in Python 3.5” on page 385 shows the @
operator which is only supported by Python 3.5.
Almost all code in the book should work with any Python 3.x
compatible interpreter,
including PyPy3 2.4.0 which is compatible with Python 3.2.5. A
notable exception are
the examples using yield from and asyncio, which are only available
in Python 3.3 or
later.
Most code should also work with Python 2.7 with minor changes,
except the Unicode-
Preface | xix
Conventions Used in This Book
XXXrevise
Italic Indicates new terms, URLs, email addresses, filenames, and file
extensions.
Constant width
the term.
mined by context.
«Guillemets»
2. In the Python docs, square brackets are used for this purpose, but
I have seen people confuse them with list displays.
xx | Preface
Using Code Examples
Every script and most code snippets that appear in the book are
available in the flu
https://github.com/oreillymedia/title_title.
This book is here to help you get your job done. In general, if
example code is offered
with this book, you may use it in your programs and documentation.
You do not need
ample code from this book into your product’s documentation does
require permission.
author, publisher, and ISBN. For example: “Book Title by Some Author
(O’Reilly).
If you feel your use of code examples falls outside fair use or the
permission given above,
ogy, and dozens more. For more information about Safari Books
Online, please visit us
online.
Preface | xxi
How to Contact Us
Sebastopol, CA 95472
We have a web page for this book, where we list errata, examples,
and any additional
tions@oreilly.com.
at http://www.oreilly.com.
Acknowledgments
simple and clear. Guido van Rossum, son of an architect and brother
of a master font
value to the book. Victor Stinner kindly reviewed Chapter 18, bringing
his expertise as xxii | Preface
—Sans toi, je ne puis plus vivre!… sans toi, je ne puis que mourir!…
Un éclair traversa le vert de ses prunelles. Elle dit d'une voix plus
basse, presque rauque:
Et, souriant d'un sourire rouge qui me fit courir un frisson dans les
moelles, elle dit encore:
—Clara…
—Chut!… N'êtes-vous pas mon bébé, cher petit cœur?… Vous devez
obéir… Et puis, vous ne savez pas…
Il avait été décidé que, les deux jours que nous relâchions à
Colombo, nous les passerions, Clara et moi, à visiter la ville et les
environs, où mon amie avait séjourné et qu'elle connaissait à
merveille. Il y faisait une chaleur torride, si torride que les endroits
les plus frais—par comparaison—de cet atroce pays, où des savants
placent le Paradis terrestre, tels les jardins au bord des grèves, me
parurent d'étouffantes étuves. La plupart de nos compagnons de
voyage n'osèrent pas affronter cette température de feu, qui leur
enlevait la moindre velléité de sortir et jusqu'au plus vague désir de
remuer. Je les vois encore, ridicules et gémissants, dans le grand hall
de l'hôtel, le crâne couvert de serviettes mouillées et fumantes,
élégant appareil renouvelé tous les quarts d'heure, qui transformait
la plus noble partie de leur individu en un tuyau de cheminée,
couronné de son panache de vapeur. Étendus sur des fauteuils à
bascule, sous le punka, la cervelle liquéfiée, les poumons
congestionnés, ils buvaient des boissons glacées que leur
préparaient des boys, lesquels, par la couleur de la peau et la
structure du corps, rappelaient les naïfs bonshommes en pain
d'épice de nos foires parisiennes, tandis que d'autres boys, de même
ton et de même gabarit, éloignaient d'eux, à grands coups
d'éventail, les moustiques.
C'était un homme très long, très mince, très sec, très rouge de
visage, et dont la barbe blanche descendait jusqu'au nombril,
coupée carrément, ainsi qu'une queue de poney. Il portait un large
pantalon de soie jaune, et son torse velu s'enveloppait dans une
sorte de châle de laine claire. Il lut avec gravité la lettre que je lui
remis et, après m'avoir examiné du coin de l'œil avec un air méfiant
—se méfiait-il de moi ou de lui?—il me demanda:
—Dans le mer?…
—Yès!… Yès…
Je saluai profondément.
—Yès!…
—Ô bébé!… bébé… bébé… que vous êtes drôle, cher petit voyou!…
—Comment?… Vous ne savez pas?… Mais Annie est morte, cher petit
cœur…
—Et ce n'est pas tout!… Maintes fois, Annie avait manifesté le désir
d'être emportée, quand elle serait morte, au petit cimetière des
Parsis… là-bas… sur la colline du Chien Bleu… Elle voulait que son
corps fût déchiré par le bec des vautours… Vous savez combien elle
avait des idées singulières et violentes en toutes choses!… Eh bien,
les vautours refusèrent ce festin royal, qu'elle leur offrait… Ils
s'éloignèrent, en poussant d'affreux cris, de son cadavre… Il fallut le
brûler…
Avec des gestes lents et charmants, Clara lissa l'or roux de ses
cheveux, caressa la fourrure rouge du chien qui s'était réveillé, et
elle dit négligemment:
—Est-ce que mes seins vous plaisent toujours?… Est-ce que vous me
trouvez toujours belle?… Alors, pourquoi êtes-vous parti si… si
longtemps? Oui… oui… je sais… ne dites rien… ne répondez rien… je
sais… Vous êtes une petite bête, cher amour!…
—Oh! demain… répondit Clara, avec des moues étonnées et des airs
de doux reproche… toujours demain!… Vous ne savez donc pas que
c'est impossible demain?… Demain?… mais c'est tout à fait
défendu… Les portes du bagne sont fermées… même pour moi… On
ne peut donner à manger aux forçats que le mercredi; comment ne
le savez-vous pas?… Si nous manquons cette visite aujourd'hui, il
nous faudra attendre, toute une longue, longue semaine… Comme
ce serait ennuyeux!… Toute une semaine, pensez donc!… Venez,
petite chiffe adorée… oh! venez, je vous en prie… Vous pouvez bien
faire cela pour moi…
—Puisque c'est si beau, ma chère Clara… et que cela vous fait tant
de plaisir… répondis-je mélancoliquement… allons donner à manger
aux forçats…
—Ah! comme nous allons nous amuser, chère petite âme… Quand je
vais aux forçats… ça me donne le vertige… et j'ai, dans tout le corps,
des secousses pareilles à de l'amour… il me semble, vois-tu… il me
semble que je descends au fond de ma chair… tout au fond des
ténèbres de ma chair… Ta bouche… donne-moi ta bouche… ta
bouche… ta bouche… ta bouche!…
Je n'étais plus très triste, je n'étais plus très las… Le baiser de Clara,
dont j'avais, sur les lèvres, le goût—comme un magique goût
d'opium—insensibilisait mes souffrances, ralentissait les pulsations
de ma fièvre, éloignait jusqu'à l'invisible l'image monstrueuse d'Annie
morte… Et je regardai le jardin d'un regard apaisé…
Apaisé?…
Apaisé?…
—Vite! vite!… mon chéri… Car il faut que nous fassions le grand
tour… Je mettrai mes gants en route… Allons… Venez!… Non… non…
pas vous!… ajouta-t-elle, en repoussant doucement le chien qui
jappait, bondissait, frétillait de la queue…
Elle appela un boy et lui recommanda de nous suivre avec le panier
à viande et la petite fourche.
Et nous nous mîmes en marche par le soleil, par l'affreux soleil qui
noircissait l'herbe, fanait toutes les pivoines du jardin, et me pesait
au crâne, ainsi qu'un lourd casque de plomb.
II
Clara marchait vite, sans pitié pour ma fatigue, sans souci du soleil
qui embrasait l'atmosphère et, malgré nos parasols, nous brûlait la
peau; elle marchait libre, souple, hardie, heureuse. Parfois, sur un
ton de reproche enjoué, elle me disait:
—Que vous êtes lent, chéri… Dieu que vous êtes lent!… Vous
n'avancez pas… Pourvu que les portes du bagne ne soient pas
ouvertes quand nous arriverons et que les forçats ne soient pas
gavés!… Ce serait affreux!… Oh! comme je vous détesterais!
—Amusants, pas?… me dit Clara… Et ils sont plus de trente mille qui
n'ont pas d'autre domicile que leurs bateaux!… Par exemple, le
diable seul sait ce qu'ils font!…
Et, fouillant dans les bassines, ils brandissent, comme des drapeaux,
au bout de longs crochets de fer, d'ignobles quartiers de viande
sanieuse, et, avec d'atroces grimaces qu'accentuent les rouges
balafres de leurs visages peints ainsi que des masques, ils répètent
parmi le retentissement enragé des gongs et les clameurs
concurrentes:
Clara prit l'amour de petite fourche des mains du boy qui nous
suivait avec son amour de panier, et elle piqua dans les bassines.
—Pique aussi, toi!… pique, cher amour!…
—Oh! comme vous êtes pâle! Et pourquoi?… N'est-ce donc pas très
amusant?…
—Mais cela ne sent pas mauvais, mon amour… Cela sent la mort,
voilà tout!…
—Vite!… vite!…
III