Python in a nutshell Second Edition Alex Martelli - The complete ebook version is now available for download
Python in a nutshell Second Edition Alex Martelli - The complete ebook version is now available for download
https://ebookfinal.com/download/python-cookbook-2nd-ed-edition-alex-
martelli/
https://ebookfinal.com/download/quantum-field-theory-in-a-nutshell-
second-edition-a-zee/
https://ebookfinal.com/download/sql-in-a-nutshell-3rd-edition-kevin-
kline/
https://ebookfinal.com/download/c-in-a-nutshell-1st-ed-edition-ray-
lischner/
Algorithms in a Nutshell 1st Edition George T. Heineman
https://ebookfinal.com/download/algorithms-in-a-nutshell-1st-edition-
george-t-heineman/
https://ebookfinal.com/download/java-in-a-nutshell-2nd-ed-edition-
david-flanagan/
https://ebookfinal.com/download/cisco-ios-in-a-nutshell-2nd-ed-
edition-james-boney/
https://ebookfinal.com/download/lpi-linux-certification-in-a-nutshell-
third-edition-adam-haeder/
https://ebookfinal.com/download/ruby-in-a-nutshell-a-desktop-quick-
reference-1st-edition-yukihiro-matsumoto/
Python in a nutshell Second Edition Alex Martelli Digital
Instant Download
Author(s): Alex Martelli
ISBN(s): 9780596100469, 0596100469
Edition: Second
File Details: PDF, 12.99 MB
Year: 2006
Language: english
PYTHON
IN A NUTSHELL
Second Edition
Alex Martelli
Printing History:
March 2003: First Edition.
July 2006: Second Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered
trademarks of O’Reilly Media, Inc. The In a Nutshell series designations, Python in a Nutshell,
the image of an African rock python, 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 trademark 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
author assume no responsibility for errors or omissions, or for damages resulting from the use
of the information contained herein.
ISBN: 978-0596-10046-9
[LSI] [2011-07-01]
Chapter 1
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
2. Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Installing Python from Source Code 14
Installing Python from Binaries 18
Installing Jython 20
Installing IronPython 21
iii
Part II. Core Python Language and Built-ins
4. The Python Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Lexical Structure 33
Data Types 38
Variables and Other References 46
Expressions and Operators 50
Numeric Operations 52
Sequence Operations 53
Set Operations 58
Dictionary Operations 59
The print Statement 61
Control Flow Statements 62
Functions 70
5. Object-Oriented Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Classes and Instances 82
Special Methods 104
Decorators 115
Metaclasses 116
6. Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
The try Statement 121
Exception Propagation 126
The raise Statement 128
Exception Objects 129
Custom Exception Classes 132
Error-Checking Strategies 134
7. Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Module Objects 139
Module Loading 144
Packages 149
The Distribution Utilities (distutils) 150
iv | Table of Contents
The functional Module 175
The bisect Module 176
The heapq Module 177
The UserDict Module 178
The optparse Module 179
The itertools Module 183
Table of Contents | v
12. Time Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
The time Module 302
The datetime Module 306
The pytz Module 313
The dateutil Module 313
The sched Module 316
The calendar Module 317
The mx.DateTime Module 319
vi | Table of Contents
17. Tkinter GUIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Tkinter Fundamentals 406
Widget Fundamentals 408
Commonly Used Simple Widgets 415
Container Widgets 420
Menus 423
The Text Widget 426
The Canvas Widget 436
Layout Management 442
Tkinter Events 446
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
Preface
ix
mentions text editors that are particularly suitable for editing Python
programs and auxiliary programs for thoroughly checking your Python
sources, and examines some full-fledged integrated development environ-
ments, including IDLE, which comes free with standard Python.
x | Preface
specific issue of registering “clean-up” functions to be executed at program-
termination time.
Chapter 14, Threads and Processes
Covers Python’s functionality for concurrent execution, both via multiple
threads running within one process and via multiple processes running on a
single machine. The chapter also covers how to access the process’s environ-
ment, and how to access files via memory-mapping mechanisms.
Chapter 15, Numeric Processing
Shows Python’s features for numeric computations, both in standard library
modules and in third-party extension packages; in particular, the chapter
covers how to use decimal floating-point numbers instead of the default
binary floating-point numbers. The chapter also covers how to get and use
pseudorandom and truly random numbers.
Chapter 16, Array Processing
Covers built-in and extension packages for array handling, focusing on the
traditional Numeric third-party extension, and mentions other, more recently
developed alternatives.
Chapter 17, Tkinter GUIs
Explains how to develop graphical user interfaces in Python with the Tkinter
package included with the standard Python distribution, and briefly mentions
other alternative Python GUI frameworks.
Chapter 18, Testing, Debugging, and Optimizing
Deals with Python tools and approaches that help ensure your programs are
correct (i.e., that your programs do what they’re meant to do), find and
correct errors in your programs, and check and enhance your programs’
performance. The chapter also covers the concept of “warning” and the
Python library module that deals with it.
Preface | xi
Chapter 22, MIME and Network Encodings
Shows how to process email and other network-structured and encoded
documents in Python.
Chapter 23, Structured Text: HTML
Covers Python library modules that let you process and generate HTML
documents.
Chapter 24, Structured Text: XML
Covers Python library modules and popular extensions that let you process,
modify, and generate XML documents.
Reference Conventions
In the function/method reference entries, when feasible, each optional parameter
is shown with a default value using the Python syntax name=value. Built-in func-
tions need not accept named parameters, so parameter names are not significant.
Some optional parameters are best explained in terms of their presence or
absence, rather than through default values. In such cases, I indicate that a param-
eter is optional by enclosing it in brackets ([]). When more than one argument is
optional, the brackets are nested.
Typographic Conventions
Italic
Used for filenames, program names, URLs, and to introduce new terms. Also
used for Unix commands and their options.
Constant width
Used for all code examples, as well as for all items that appear in code,
including keywords, methods, functions, classes, and modules.
xii | Preface
Constant width italic
Used to show text that can be replaced with user-supplied values in code
examples.
Constant width bold
Used for commands that must be typed on the command line, and occasion-
ally for emphasis in code examples or to indicate code output.
How to Contact Us
I have tested and verified the information in this book to the best of my ability,
but you may find that features have changed (or even that I have made mistakes!).
Please let the publisher know about any errors you find, as well as your sugges-
tions for future editions, by writing to:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-928-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
There is a web page for this book, which lists errata, examples, and any addi-
tional information. You can access this page at:
http://www.oreilly.com/catalog/pythonian2
To ask technical questions or comment on the book, send email to:
bookquestions@oreilly.com
For more information about books, conferences, resource centers, and the
O’Reilly Network, see the O’Reilly web site at:
http://www.oreilly.com
Preface | xiii
Safari® Enabled
When you see a Safari® Enabled icon on the cover of your favorite
technology book, that means the book is available online through
the O’Reilly Network Safari Bookshelf.
Safari offers a solution that’s better than e-books: it’s a virtual
library that lets you easily search thousands of top tech books, cut and paste code
samples, download chapters, and find quick answers when you need the most
accurate, current information. Try it for free at http://safari.oreilly.com.
Acknowledgments
My heartfelt thanks to everybody who helped me out on this book, both in the
first edition and in its current second edition. Many Python beginners, practitio-
ners, and experts have read drafts of parts of the book and have offered feedback
to help me make the book clear, precise, accurate, and readable. Out of all of
them, for the quality and quantity of their feedback and other help, I must single
out for special thanks my colleagues at Google, especially Neal Norwitz and
Mohsin Ahmed.
The first edition received indispensable help from Python experts in specific areas
(Aahz on threading, Itamar Shtull-Trauring on Twisted, Mike Orr on Cheetah,
Eric Jones and Paul Dubois on Numeric, and Tim Peters on threading, testing,
and optimization), a wonderful group of technical reviewers (Fred Drake, Magnus
Lie Hetland, Steve Holden, and Sue Giller), and the book’s editor, Paula
Ferguson. The second edition benefited from the efforts of editors Jonathan
Gennick and Mary O’Brien, and technical reviewers Ryan Alexander, Jeffery
Collins, and Mary Gardiner. I owe special thanks to the wonderful folks in the
O’Reilly Tools Group, who (both directly and personally, and through the helpful
tools they developed) helped me through several difficult technical problems.
As always, even though they’re back in my native Italy and my career with Google
has taken me to California, my thoughts go to my family: my children Flavia and
Lucio, my sister Elisabetta, and my father Lanfranco.
But the one, incredible individual to which my heart gushes out in gratitude, and
more than gratitude, is my wife, Anna Martelli Ravenscroft, my co-author in the
second edition of the Python Cookbook, a fellow Python Software Foundation
member, and the harshest, most wonderful technical reviewer any author could
possibly dream of. Besides her innumerable direct contributions to this book,
Anna managed to create for me, out of thin air, enough peace, quiet, and free time
over the last year (despite my wonderful and challenging responsibilities as Uber
Tech Lead for Google) to make this book possible. Truly, this is her book at least
as much as it is mine.
xiv | Preface
Getting Started with Python
I
Introduction to Python
1
3
Python is simple, but not simplistic. It adheres to the idea that if a language
behaves a certain way in some contexts, it should ideally work similarly in all
contexts. Python also follows the principle that a language should not have
“convenient” shortcuts, special cases, ad hoc exceptions, overly subtle distinc-
tions, or mysterious and tricky under-the-covers optimizations. A good language,
like any other designed artifact, must balance such general principles with taste,
common sense, and a high degree of practicality.
Python is a general-purpose programming language, so Python’s traits are useful
in just about any area of software development. There is no area where Python
cannot be part of an optimal solution. “Part” is an important word here; while
many developers find that Python fills all of their needs, Python does not have to
stand alone. Python programs can easily cooperate with a variety of other soft-
ware components, making it an ideal language for gluing together components
written in other languages.
Python is a very-high-level language (VHLL). This means that Python uses a
higher level of abstraction, conceptually farther from the underlying machine,
than do classic compiled languages such as C, C++, and Fortran, which are tradi-
tionally called high-level languages. Python is also simpler, faster to process, and
more regular than classic high-level languages. This affords high programmer
productivity and makes Python an attractive development tool. Good compilers
for classic compiled languages can often generate binary machine code that runs
much faster than Python code. However, in most cases, the performance of
Python-coded applications proves sufficient. When it doesn’t, you can apply the
optimization techniques covered in “Optimization” on page 474 to enhance your
program’s performance while keeping the benefits of high programming
productivity.
Newer languages such as Java and C# are slightly higher-level (farther from the
machine) than classic ones such as C and Fortran, and share some characteristics
of classic languages (such as the need to use declarations) as well as some of
VHLLs like Python (such as the use of portable bytecode as the compilation target
in typical implementations, and garbage collection to relieve programmers from
the need to manage memory). If you find you are more productive with Java or
C# than with C or Fortran, try Python (possibly in the Jython or IronPython
implementations, covered in “Python Implementations” on page 5) and become
even more productive.
In terms of language level, Python is comparable to other powerful VHLLs like
Perl or Ruby. The advantages of simplicity and regularity, however, remain on
Python’s side.
Python is an object-oriented programming language, but it lets you develop code
using both object-oriented and traditional procedural styles, and a touch of the
functional programming style, too, mixing and matching as your application
requires. Python’s object-oriented features are like those of C++, although they
are much simpler to use.
Language: English
You will find yourself under the necessity of doing it in this noble
company, or alone. Try it. Strive to be perfect, as God is perfect—to
act up to your own highest idea, in connection with church or state in
this land corrupted by slavery, and see if you are helped or hindered.
Be not dragged along by them protesting. It is graceing as a slave
the chariot wheels of a triumph. But flee from them, as one flees out
of Babylon. Secure the blessing of union for good, and be delivered
from the curse of union in evil, by acting with the American Anti-
Slavery Society, its members and friends.
I use this mode of expression advisedly, for I am not speaking of a
mere form of association. Many are in harmonious coöperation with
it who have neither signed the constitution nor subscribed the annual
half dollar. Hence it is neither a formality nor a ceremony, but a
united, onward-flowing current of noble lives.
If, then, you feel that devotedness of heart which I verily think your
question indicates, I feel free to counsel you to go immediately to the
nearest office of the American Anti-Slavery Society,[1] by letter, if not
in person, subscribe what money you can afford—the first fruits of a
life-long liberality, and study the cause like a science, while
promoting it like a gospel, under the cheering and helpful sympathy
of some of the best company on earth; but not unless; for this
company despises what politicians, ecclesiastical and other, call
“getting people committed.” They have a horror of this selfish
invasion of another’s freedom, as of the encumbrance of selfish
help. They warn you not to touch the ark with unhallowed hands.
One consideration more—the thought of what you owe to your
forerunners in what you feel to be the truth. It is, to follow meekly
after, and be baptized with the baptism that they are baptized with.
“Thus it becometh us to fulfil all righteousness;” and the more your
talents, gifts, and graces may, in your own judgment, be superior to
theirs, the more becoming it will be to seek their fellowship; for in the
whole land they, and they alone, are right. It is not eulogy, but fact,
that theirs is the path of the just, shining more and more unto the
perfect day—denied only by the besotted with injustice, the
committed to crime. Consider, then, not only what you owe to your
slavery-cursed country, your enslaving as well as enslaved
countrymen, your fathers’ memory, your remotest posterity, the
Christian religion, which forbids the sacrifice of one man’s rights to
another man’s interests, and which knows no distinction of caste,
color, or condition,—but consider, also, what you owe to those
individuals and to that brotherhood who have battled twenty years in
the breach for your freedom, involved with that of the meanest slave.
Imagine how the case stood with those who perished by suffocation
in the Black Hole at Calcutta. Suppose that some of their number
had felt the sublime impulse to place their bodies in the door, and the
high devoted hearts to stand the crushing till dawn awoke the tyrant;
the rest of that doomed band might have passed out alive. This is
what the American Anti-Slavery Society has been unflinchingly doing
for you, and for the rest of the nation, amid torture, insult, and
curses, through a long night of terror and despair. The life of the
land, its precious moral sense, has been thus kept from suffocation.
The free agitating air of faithful speech has saved it. The soul of the
United States is not dead, thanks, under Providence, to that noble
fellowship of resolute souls, to find whom the nation has been
winnowed. Do your duty by them, in the name of self-respect. Such
companionship is an honor accorded to but few, and of that worthy
few I would fain count you one. Strike, then, with them at the
existence of slavery, and you will see individual slaves made free,
anti-slavery leaven introduced into parties and churches, instruction
diffused, the products of free labor multiplied, and fugitives
protected, in exact proportion to the energy of the grand onset
against the civil system.
Whereas the Most High God “hath made of one blood all nations of
men to dwell on all the face of the earth,” and hath commanded them
to love their neighbors as themselves; and whereas our national
existence is based upon this principle, as recognized in the
Declaration of Independence, “that all mankind are created equal,
and that they are endowed by their Creator with certain inalienable
rights, among which are life, liberty, and the pursuit of happiness;”
and whereas, after the lapse of nearly sixty years, since the faith and
honor of the American people were pledged to this avowal before
Almighty God and the world, nearly one sixth part of the nation are
held in bondage by their fellow-citizens; and whereas slavery is
contrary to the principles of natural justice, of our republican form of
government, and of the Christian religion, and is destructive of the
prosperity of the country, while it is endangering the peace, union,
and liberties of the States; and whereas we believe it the duty and
interest of the masters immediately to emancipate their slaves, and
that no scheme of expatriation, either voluntary or by compulsion,
can remove this great and increasing evil; and whereas we believe
that it is practicable, by appeals to the consciences, hearts, and
interests of the people, to awaken a public sentiment throughout the
nation that will be opposed to the continuance of slavery in any part
of the republic, and by effecting the speedy abolition of slavery,
prevent a general convulsion; and whereas we believe we owe it to
the oppressed, to our fellow-citizens who hold slaves, to our whole
country, to posterity, and to God, to do all that is lawfully in our power
to bring about the extinction of slavery, we do hereby agree, with a
prayerful reliance on the divine aid, to form ourselves into a society
to be governed by the following constitution:—
Article I.—This society shall be called the American Anti-Slavery
Society.
Article II.—The objects of this society are the entire abolition of
slavery in the United States. While it admits that each State in which
slavery exists has, by the constitution of the United States, the
exclusive right to legislate in regard to its abolition in said State, it
shall aim to convince all our fellow-citizens, by arguments addressed
to their understandings and consciences, that slaveholding is a
heinous crime in the sight of God, and that the duty, safety, and best
interests of all concerned require its immediate abandonment,
without expatriation. The society will also endeavor, in a
constitutional way, to influence Congress to put an end to the
domestic slave trade, and to abolish slavery in all those portions of
our common country which come under its control, especially in the
District of Columbia, and likewise to prevent the extension of it to any
State that may be hereafter admitted to the Union.
Article III.—This society shall aim to elevate the character and
condition of the people of color, by encouraging their intellectual,
moral, and religious improvement, and by removing public prejudice,
that thus they may, according to their intellectual and moral worth,
share an equality with the whites of civil and religious privileges; but
this society will never, in any way, countenance the oppressed in
vindicating their rights by resorting to physical force.
Article IV.—Any person who consents to the principles of this
constitution, who contributes to the funds of this society, and is not a
slaveholder, may be a member of this society, and shall be entitled to
vote at the meetings.
Article V.—The officers of this society shall be a president, vice-
presidents, a recording secretary, corresponding secretaries, a
treasurer, and an executive committee of not less than five nor more
than twelve members.
Article VI.—The executive committee shall have power to enact
their own by-laws, fill any vacancy in their body, and in the offices of
secretary and treasurer, employ agents, determine what
compensation shall be paid to agents and to the corresponding
secretaries, direct the treasurer in the application of all moneys, and
call special meetings of the society. They shall make arrangements
for all meetings of the society, make an annual written report of their
doings, the expenditures and funds of the society, and shall hold
stated meetings, and adopt the most energetic measures in their
power to advance the objects of the society. They may, if they shall
see fit, appoint a board of assistant managers, composed of not less
than three nor more than seven persons residing in New York city, or
its vicinity, whose duty it shall be to render such assistance to the
committee in conducting the affairs of the society as the exigencies
of the cause may require. To this board they may from time to time
confide such of their own powers as they may deem necessary to
the efficient conduct of the society’s business. The board shall keep
a record of its proceedings, and furnish a copy of the same for the
information of the committee, as often as may be required.
Article VII.—The president shall preside at all meetings of the
society, or, in his absence, one of the vice-presidents, or, in their
absence, a president pro tem. The corresponding secretaries shall
conduct the correspondence of the society. The recording secretary
shall notify all meetings of the society and of the executive
committee, and shall keep records of the same in separate books.
The treasurer shall collect the subscriptions, make payments at the
direction of the executive committee, and present a written and
audited account to accompany the annual report.
Article VIII.—The annual meeting of the society shall be held each
year at such time and place as the executive committee may direct,
when the accounts of the treasurer shall be presented, the annual
report read, appropriate addresses delivered, the officers chosen,
and such other business transacted as shall be deemed expedient.
Article IX.—Any anti-slavery society or association founded on the
same principles may become auxiliary to this society. The officers of
each auxiliary society shall be ex officio members of the parent
institution, and shall be entitled to deliberate and vote in the
transactions of its concerns.
Article X.—This constitution may be amended, at any annual
meeting of the society, by a vote of two thirds of the members
present, provided the amendments proposed have been previously
submitted, in writing, to the executive committee.
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.
ebookfinal.com