Python Cookbook 3rd Edition David Beazley PDF Download
Python Cookbook 3rd Edition David Beazley PDF Download
https://ebookultra.com/download/python-cookbook-3rd-edition-david-
beazley/
https://ebookultra.com/download/python-cookbook-third-edition-beazley/
https://ebookultra.com/download/python-cookbook-3ed-edition-beazley-d/
https://ebookultra.com/download/python-cookbook-1st-edition-alex-
martelli/
https://ebookultra.com/download/maya-programming-with-python-
cookbook-1st-edition-herbez/
Python Data Visualization Cookbook 2nd Edition Igor
Milovanovic
https://ebookultra.com/download/python-data-visualization-
cookbook-2nd-edition-igor-milovanovic/
https://ebookultra.com/download/php-cookbook-solutions-examples-for-
php-programmers-3rd-edition-david-sklar/
https://ebookultra.com/download/functional-programming-in-python-1st-
edition-david-mertz/
https://ebookultra.com/download/puppet-cookbook-3rd-edition-thomas-
uphill/
Python Cookbook 3rd Edition David Beazley Digital
Instant Download
Author(s): David Beazley, Brian K. Jones
ISBN(s): 9781449340360, 1449340369
Edition: 3
File Details: PDF, 9.64 MB
Year: 2013
Language: english
THIRD EDITION
Python Cookbook
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly
Media, Inc. Python Cookbook, the image of a springhaas, and related trade dress are trademarks of O’Reilly
Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐
mark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and authors assume
no responsibility for errors or omissions, or for damages resulting from the use of the information contained
herein.
ISBN: 978-1-449-34037-7
[LSI]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
iii
2.5. Searching and Replacing Text 45
2.6. Searching and Replacing Case-Insensitive Text 46
2.7. Specifying a Regular Expression for the Shortest Match 47
2.8. Writing a Regular Expression for Multiline Patterns 48
2.9. Normalizing Unicode Text to a Standard Representation 50
2.10. Working with Unicode Characters in Regular Expressions 52
2.11. Stripping Unwanted Characters from Strings 53
2.12. Sanitizing and Cleaning Up Text 54
2.13. Aligning Text Strings 57
2.14. Combining and Concatenating Strings 58
2.15. Interpolating Variables in Strings 61
2.16. Reformatting Text to a Fixed Number of Columns 64
2.17. Handling HTML and XML Entities in Text 65
2.18. Tokenizing Text 66
2.19. Writing a Simple Recursive Descent Parser 69
2.20. Performing Text Operations on Byte Strings 78
iv | Table of Contents
4.7. Taking a Slice of an Iterator 122
4.8. Skipping the First Part of an Iterable 123
4.9. Iterating Over All Possible Combinations or Permutations 125
4.10. Iterating Over the Index-Value Pairs of a Sequence 127
4.11. Iterating Over Multiple Sequences Simultaneously 129
4.12. Iterating on Items in Separate Containers 131
4.13. Creating Data Processing Pipelines 132
4.14. Flattening a Nested Sequence 135
4.15. Iterating in Sorted Order Over Merged Sorted Iterables 136
4.16. Replacing Infinite while Loops with an Iterator 138
Table of Contents | v
6.8. Interacting with a Relational Database 195
6.9. Decoding and Encoding Hexadecimal Digits 197
6.10. Decoding and Encoding Base64 199
6.11. Reading and Writing Binary Arrays of Structures 199
6.12. Reading Nested and Variable-Sized Binary Structures 203
6.13. Summarizing Data and Performing Statistics 214
7. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
7.1. Writing Functions That Accept Any Number of Arguments 217
7.2. Writing Functions That Only Accept Keyword Arguments 219
7.3. Attaching Informational Metadata to Function Arguments 220
7.4. Returning Multiple Values from a Function 221
7.5. Defining Functions with Default Arguments 222
7.6. Defining Anonymous or Inline Functions 224
7.7. Capturing Variables in Anonymous Functions 225
7.8. Making an N-Argument Callable Work As a Callable with Fewer
Arguments 227
7.9. Replacing Single Method Classes with Functions 231
7.10. Carrying Extra State with Callback Functions 232
7.11. Inlining Callback Functions 235
7.12. Accessing Variables Defined Inside a Closure 238
vi | Table of Contents
8.20. Calling a Method on an Object Given the Name As a String 305
8.21. Implementing the Visitor Pattern 306
8.22. Implementing the Visitor Pattern Without Recursion 311
8.23. Managing Memory in Cyclic Data Structures 317
8.24. Making Classes Support Comparison Operations 321
8.25. Creating Cached Instances 323
9. Metaprogramming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
9.1. Putting a Wrapper Around a Function 329
9.2. Preserving Function Metadata When Writing Decorators 331
9.3. Unwrapping a Decorator 333
9.4. Defining a Decorator That Takes Arguments 334
9.5. Defining a Decorator with User Adjustable Attributes 336
9.6. Defining a Decorator That Takes an Optional Argument 339
9.7. Enforcing Type Checking on a Function Using a Decorator 341
9.8. Defining Decorators As Part of a Class 345
9.9. Defining Decorators As Classes 347
9.10. Applying Decorators to Class and Static Methods 350
9.11. Writing Decorators That Add Arguments to Wrapped Functions 352
9.12. Using Decorators to Patch Class Definitions 355
9.13. Using a Metaclass to Control Instance Creation 356
9.14. Capturing Class Attribute Definition Order 359
9.15. Defining a Metaclass That Takes Optional Arguments 362
9.16. Enforcing an Argument Signature on *args and **kwargs 364
9.17. Enforcing Coding Conventions in Classes 367
9.18. Defining Classes Programmatically 370
9.19. Initializing Class Members at Definition Time 374
9.20. Implementing Multiple Dispatch with Function Annotations 376
9.21. Avoiding Repetitive Property Methods 382
9.22. Defining Context Managers the Easy Way 384
9.23. Executing Code with Local Side Effects 386
9.24. Parsing and Analyzing Python Source 388
9.25. Disassembling Python Byte Code 392
Table of Contents | ix
15.10. Wrapping Existing C Code with Cython 632
15.11. Using Cython to Write High-Performance Array Operations 638
15.12. Turning a Function Pointer into a Callable 643
15.13. Passing NULL-Terminated Strings to C Libraries 644
15.14. Passing Unicode Strings to C Libraries 648
15.15. Converting C Strings to Python 653
15.16. Working with C Strings of Dubious Encoding 654
15.17. Passing Filenames to C Extensions 657
15.18. Passing Open Files to C Extensions 658
15.19. Reading File-Like Objects from C 659
15.20. Consuming an Iterable from C 662
15.21. Diagnosing Segmentation Faults 663
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
x | Table of Contents
Preface
Since 2008, the Python world has been watching the slow evolution of Python 3. It was
always known that the adoption of Python 3 would likely take a long time. In fact, even
at the time of this writing (2013), most working Python programmers continue to use
Python 2 in production. A lot has been made about the fact that Python 3 is not backward
compatible with past versions. To be sure, backward compatibility is an issue for anyone
with an existing code base. However, if you shift your view toward the future, you’ll find
that Python 3 offers much more than meets the eye.
Just as Python 3 is about the future, this edition of the Python Cookbook represents a
major change over past editions. First and foremost, this is meant to be a very forward
looking book. All of the recipes have been written and tested with Python 3.3 without
regard to past Python versions or the “old way” of doing things. In fact, many of the
recipes will only work with Python 3.3 and above. Doing so may be a calculated risk,
but the ultimate goal is to write a book of recipes based on the most modern tools and
idioms possible. It is hoped that the recipes can serve as a guide for people writing new
code in Python 3 or those who hope to modernize existing code.
Needless to say, writing a book of recipes in this style presents a certain editorial chal‐
lenge. An online search for Python recipes returns literally thousands of useful recipes
on sites such as ActiveState’s Python recipes or Stack Overflow. However, most of these
recipes are steeped in history and the past. Besides being written almost exclusively for
Python 2, they often contain workarounds and hacks related to differences between old
versions of Python (e.g., version 2.3 versus 2.4). Moreover, they often use outdated
techniques that have simply become a built-in feature of Python 3.3. Finding recipes
exclusively focused on Python 3 can be a bit more difficult.
Rather than attempting to seek out Python 3-specific recipes, the topics of this book are
merely inspired by existing code and techniques. Using these ideas as a springboard,
the writing is an original work that has been deliberately written with the most modern
Python programming techniques possible. Thus, it can serve as a reference for anyone
who wants to write their code in a modern style.
xi
In choosing which recipes to include, there is a certain realization that it is simply
impossible to write a book that covers every possible thing that someone might do with
Python. Thus, a priority has been given to topics that focus on the core Python language
as well as tasks that are common to a wide variety of application domains. In addition,
many of the recipes aim to illustrate features that are new to Python 3 and more likely
to be unknown to even experienced programmers using older versions. There is also a
certain preference to recipes that illustrate a generally applicable programming tech‐
nique (i.e., programming patterns) as opposed to those that narrowly try to address a
very specific practical problem. Although certain third-party packages get coverage, a
majority of the recipes focus on the core language and standard library.
xii | Preface
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program elements
such as variable or function names, databases, data types, environment variables,
statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.
Preface | xiii
of example code from this book into your product’s documentation does require per‐
mission.
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: Python Cookbook, 3rd edition, by David
Beazley and Brian K. Jones (O’Reilly). Copyright 2013 David Beazley and Brian Jones,
978-1-449-34037-7.
If you feel your use of code examples falls outside fair use or the permission given here,
feel free to contact us at [email protected].
How to Contact Us
Please address comments and questions concerning this book to the publisher:
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://oreil.ly/python_cookbook_3e.
xiv | Preface
To comment or ask technical questions about this book, send email to bookques
[email protected].
For more information about our books, courses, conferences, and news, see our website
at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
We would like to acknowledge the technical reviewers, Jake Vanderplas, Robert Kern,
and Andrea Crotti, for their very helpful comments, as well as the general Python com‐
munity for their support and encouragement. We would also like to thank the editors
of the prior edition, Alex Martelli, Anna Ravenscroft, and David Ascher. Although this
edition is newly written, the previous edition provided an initial framework for selecting
the topics and recipes of interest. Last, but not least, we would like to thank readers of
the early release editions for their comments and suggestions for improvement.
Preface | xv
Brian Jones’ Acknowledgments
I would like to thank both my coauthor, David Beazley, as well as Meghan Blanchette
and Rachel Roumeliotis of O’Reilly, for working with me on this project. I would also
like to thank my amazing wife, Natasha, for her patience and encouragement in this
project, and her support in all of my ambitions. Most of all, I’d like to thank the Python
community at large. Though I have contributed to the support of various open source
projects, languages, clubs, and the like, no work has been so gratifying and rewarding
as that which has been in the service of the Python community.
Brian K. Jones
http://www.protocolostomy.com
https://twitter.com/bkjones
xvi | Preface
CHAPTER 1
Data Structures and Algorithms
Python provides a variety of useful built-in data structures, such as lists, sets, and dic‐
tionaries. For the most part, the use of these structures is straightforward. However,
common questions concerning searching, sorting, ordering, and filtering often arise.
Thus, the goal of this chapter is to discuss common data structures and algorithms
involving data. In addition, treatment is given to the various data structures contained
in the collections module.
Solution
Any sequence (or iterable) can be unpacked into variables using a simple assignment
operation. The only requirement is that the number of variables and structure match
the sequence. For example:
>>> p = (4, 5)
>>> x, y = p
>>> x
4
>>> y
5
>>>
1
'ACME'
>>> date
(2012, 12, 21)
Discussion
Unpacking actually works with any object that happens to be iterable, not just tuples or
lists. This includes strings, files, iterators, and generators. For example:
>>> s = 'Hello'
>>> a, b, c, d, e = s
>>> a
'H'
>>> b
'e'
>>> e
'o'
>>>
When unpacking, you may sometimes want to discard certain values. Python has no
special syntax for this, but you can often just pick a throwaway variable name for it. For
example:
>>> data = [ 'ACME', 50, 91.1, (2012, 12, 21) ]
>>> _, shares, price, _ = data
>>> shares
50
>>> price
91.1
>>>
However, make sure that the variable name you pick isn’t being used for something else
already.
T H E R A P E O F T H E LO C K .
T H E R A P E O F T H E LO C K .
With this his memorandum ends; and I regret that he has not
recorded the prices he received for the pictures. Mr. Nichols
conjectures that they were originally very low; he is most probably
right with respect to those that were painted in the early part of
Hogarth's life. But let it be recollected that for the portrait of Garrick
in Richard III. he received two hundred pounds, which, as the artist
himself remarks, was a more liberal remuneration than had been
paid to any contemporary painter. When my late friend Mr.
Gainsborough began to paint portraits at Bath (at a period when
much higher prices were paid), his general rule was five guineas for
a three-quarters portrait.
Below is inserted a copy from one of Hogarth's early engravings,
the arms of the Duchess of Kendal, mistress to George I., probably
done on a piece of plate at the time he was Gamble's apprentice.
The original, of the same size, is in the Editor's possession. It is
drawn in a correct and spirited style; and considering the age of the
artist, and the purpose for which it was engraven, not demanding
much attention or exertion, gave some promise of the excellence
which he afterwards attained.
In this point of view, to an admirer of Hogarth it becomes in some
degree interesting, which will, I hope, plead my apology for the
insertion of this solitary specimen of his boyish heraldry. On no other
ground should so insignificant a production as a coat of arms have
found a place in this volume.
T H E K E N D A L A R M S.
CHAPTER II.
C A P TA I N T H O M AS C O R A M
was born in the year 1668, bred to the sea, and passed the first part
of his life as master of a vessel trading to the colonies. While he
resided in the vicinity of Rotherhithe, his avocations obliging him to
go early into the city and return late, he frequently saw deserted
infants exposed to the inclemencies of the seasons, and through the
indigence or cruelty of their parents left to casual relief or untimely
death. This naturally excited his compassion, and led him to project
the establishment of an hospital for the reception of exposed and
deserted young children; in which humane design he laboured more
than seventeen years, and at last, by his unwearied application,
obtained the Royal Charter, bearing date the 17th of October 1739,
for its incorporation.
He was highly instrumental in promoting another good design, viz.
the procuring a bounty upon naval stores imported from the colonies
to Georgia and Nova Scotia. But the charitable plan which he lived to
make some progress in, though not to complete, was a scheme for
uniting the Indians in North America more closely with the British
Government, by an establishment for the education of Indian girls.
Indeed, he spent a great part of his life in serving the public, and
with so total a disregard to his private interest, that in his old age he
was himself supported by a pension of somewhat more than an
hundred pounds a year,[25] raised for him at the solicitation of Sir
Sampson Gideon and Dr. Brocklesby, by the voluntary subscriptions
of public-spirited persons, at the head of whom was the late
Frederick Prince of Wales. On application being made to this
venerable and good old man to know whether a subscription being
opened for his benefit would not offend him, he gave this noble
answer: "I have not wasted the little wealth of which I was formerly
possessed in self-indulgence or vain expenses, and am not ashamed
to confess that in this my old age I am poor."
This singularly humane, persevering, and memorable man died at
his lodgings near Leicester Square, March 29, 1751, and was
interred, pursuant to his own desire, in the vault under the chapel of
the Foundling Hospital, where an historic epitaph records his virtues,
as Hogarth's portrait has preserved his honest countenance.
Hogarth thus resumes his narrative:—
"For the portrait of Mr. Garrick in Richard III. I was paid two
hundred pounds[26] (which was more than any English artist
ever received for a single portrait), and that, too, by the
sanction of several painters who had been previously
consulted about the price, which was not given without
mature consideration.
"Notwithstanding all this, the current remark was, that
portraits were not my province, and I was tempted to
abandon the only lucrative branch of my art, for the practice
brought the whole nest of phiz-mongers on my back, where
they buzzed like so many hornets. All these people have their
friends, whom they incessantly teach to call my women
harlots, my 'Essay on Beauty' borrowed,[27] and my
composition and engraving contemptible.
"This so much disgusted me, that I sometimes declared I
would never paint another portrait, and frequently refused
when applied to; for I found by mortifying experience, that
whoever would succeed in this branch must adopt the mode
recommended in one of Gay's fables, and make divinities of
all who sit to him.[28] Whether or not this childish affectation
will ever be done away, is a doubtful question: none of those
who have attempted to reform it have yet succeeded; nor,
unless portrait-painters in general become more honest, and
their customers less vain, is there much reason to expect they
ever will."
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.
ebookultra.com