Whether you are new to programming or a professional developer, this book’s goal is to bring you quickly up to speed on the fundamentals of the core Python language.After reading this bo
Trang 2Learning Python
Trang 3Other resources from O’Reilly
Related titles Programming Python
Python Cookbook™
Python in a Nutshell
Python Pocket ReferenceTwisted NetworkProgramming Essentials
oreilly.com oreilly.com is more than a complete catalog of O’Reilly books.
You’ll also find links to news, events, articles, weblogs, samplechapters, and code examples
oreillynet.com is the essential portal for developers interested in
open and emerging technologies, including new platforms, gramming languages, and operating systems
pro-Conferences O’Reilly brings diverse innovators together to nurture the ideas
that spark revolutionary industries We specialize in ing the latest tools and systems, translating the innovator’sknowledge into useful skills for those in the trenches Visit
document-conferences.oreilly.com for our upcoming events.
Safari Bookshelf (safari.oreilly.com) is the premier online
refer-ence library for programmers and IT professionals Conductsearches across more than 1,000 books Subscribers can zero in
on answers to time-critical questions in a matter of seconds.Read the books on your Bookshelf from cover to cover or sim-ply flip to the page you need Try it today for free
Trang 4Learning Python
THIRD EDITION
Mark Lutz
Trang 5Learning Python, Third Edition
by Mark Lutz
Copyright © 2008 O’Reilly Media, Inc All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use Online editions
are also available for most titles (safari.oreilly.com) For more information, contact our
corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com.
Editor: Tatiana Apandi
Production Editor: Sumita Mukherji
Copyeditor: Rachel Head
Proofreader: Sumita Mukherji
Indexer: Julie Hawks
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Robert Romano
Printing History:
March 1999: First Edition.
December 2003: Second Edition.
October 2007: Third Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc., Learning Python, the image of a wood rat, and related trade dress are trademarks
of O’Reilly Media, Inc.
Java ™ is a trademark of Sun Microsystems, Inc .NET is a registered trademark of Microsoft
Corporation.
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.
This book uses RepKover ™ , a durable and flexible lay-flat binding.
Trang 6To Vera You are my life.
Trang 8Table of Contents
Preface xxix
1 A Python Q&A Session 3
Trang 9It’s Easy to Use 15
2 How Python Runs Programs 22
Trang 103 How You Run Programs 34
Trang 11Part II Types and Operations
4 Introducing Python Object Types 65
Trang 125 Numbers 93
6 The Dynamic Typing Interlude 112
Trang 148 Lists and Dictionaries 152
Tuple syntax peculiarities: commas and parentheses 174
Trang 15Files in Action 178
Part III Statements and Syntax
10 Introducing Python Statements 201
Trang 16Statement rule special cases 208
Trang 18Iterators: A First Look 258
14 The Documentation Interlude 278
Trang 19Chapter Summary 293
Part IV Functions
15 Function Basics 299
Trang 20Scopes and Nested Functions 320
17 Advanced Function Topics 344
Trang 21Applying Functions to Arguments 350
Extended Generator Function Protocol: send Versus next 364
Generator Expressions: Iterators Meet List Comprehensions 365
18 Modules: The Big Picture 385
Trang 22How Imports Work 389
Trang 2320 Module Packages 415
21 Advanced Module Topics 426
Trang 24Brain Builder 445
Part VI Classes and OOP
22 OOP: The Big Picture 451
23 Class Coding Basics 465
Trang 2524 Class Coding Details 481
_ _getattr_ _ and _ _setattr_ _ Catch Attribute References 498
_ _repr_ _ and _ _str_ _ Return String Representations 500
The “Zen” of Python Namespaces: Assignments Classify Names 506
Trang 2625 Designing with Classes 518
26 Advanced Class Topics 539
Trang 27Function Decorators 556
Part VII Exceptions and Tools
27 Exception Basics 575
Example: Coding Termination Actions with try/finally 588
Example: Raising and Catching User-Defined Exceptions 593
Trang 28with/as Context Managers 596
29 Designing with Exceptions 617
Trang 29Exception Gotchas 627String Exceptions Match by Identity, Not by Value 628
Part VIII Appendixes
A Installation and Configuration 639
B Solutions to End-of-Part Exercises 646 Index 681
Trang 30This book provides an introduction to the Python programming language Python is
a popular programming language used for both standalone programs and scriptingapplications in a wide variety of domains It is free, portable, powerful, and remark-ably easy to use
Whether you are new to programming or a professional developer, this book’s goal is
to bring you quickly up to speed on the fundamentals of the core Python language.After reading this book, you will know enough about Python to apply it in whateverapplication domains you choose to explore
About This Third Edition
In the four years since the second edition of this book was published in late 2003,there have been substantial changes in Python itself, and in the topics I present inPython training sessions Although I have attempted to retain as much of the priorversion of this text as possible, this new edition reflects many recent changes in thePython language and in Python training, as well as a handful of structural changes
This Edition’s Python Language Changes
On the language front, this edition has been thoroughly updated to reflect Python 2.5and all changes to the language since the publication of the second edition (The sec-ond edition was based largely on Python 2.2, with some 2.3 features grafted on at theend of the project.) In addition, discussions of anticipated changes in the upcomingPython 3.0 release have been incorporated where appropriate Here are some of themajor language topics of which you’ll find new or expanded coverage in this edition:
• The newB if A else C conditional expression (Chapter 12)
• with/as context managers (Chapter 27)
• try/except/finally unification (Chapter 27)
• Relative import syntax (Chapter 21)
Trang 31• Generator expressions (Chapter 17).
• New generator function features (Chapter 17)
• Function decorators (Chapter 26)
• The set object type (Chapter 5)
• New built-in functions:sorted,sum,any,all,enumerate (Chapters 4 and 13)
• The decimal fixed-precision object type (Chapter 5)
• New and expanded material on files, list comprehensions, iterators, and more(Chapters 13 and 17)
• New development tools coverage: Eclipse, distutils, unittest and doctest,IDLE enhancements, Shedskin, and so on (Chapters 3 and 29)
Smaller language changes (for instance, the widespread use of Trueand False, thenew sys.exc_info for fetching exception details, and the demise of string-basedexceptions, string methods, and the apply and reduce built-ins) are discussedthroughout the book In addition, some of the features that were new in the prioredition enjoy substantially expanded coverage here, including three-limit slices, andthe arbitrary arguments call syntax that subsumesapply
This Edition’s Python Training Changes
Besides such language changes, this edition has been augmented with new topics andexamples presented in the Python training sessions I have held in recent years Forexample, you’ll find:
• A new chapter introducing built-in types (Chapter 4)
• A new chapter introducing statement syntax (Chapter 10)
• A new full chapter on dynamic typing, with enhanced coverage (Chapter 6)
• An expanded OOP introduction (Chapter 22)
• New examples for files, scopes, statement nesting, classes, exceptions, and more.Many additions and changes were made with Python beginners in mind, and sometopics have been moved to appear at the places where they have proved simplest todigest in training classes List comprehensions and iterators, for example, now maketheir initial appearance in conjunction with theforloop statement, instead of laterwith functional tools
You’ll also find that the coverage of many original core language topics has been stantially expanded in this edition, with new discussions and examples added.Because this text has become something of a de facto standard resource for learningthe core Python language, the presentation has been made more complete and aug-mented with new use cases throughout
Trang 32sub-In addition, this entire edition integrates a new set of Python tips and tricks, gleanedfrom teaching classes during the last 10 years, and using Python for real work overthe last 15 The exercises have also been updated and expanded to reflect currentPython best practices, new language features, and common beginners’ mistakeswitnessed firsthand in classes Overall, the core language coverage provided by thisedition is larger than in previous editions, both because Python is larger, and becauseI’ve added contextual information that has proved to be important in practice.
This Edition’s Structural Changes
As in the prior edition, to accommodate the fact that this book is now more plete, its material has been split into bite-sized chunks That is, I’ve organized thecore language material into many multichapter parts to make the material easier totackle Types and statements, for instance, are now two top-level parts, with onechapter for each major type and statement topic This new structure is designed toallow the book to say more without intimidating readers In the process, exercisesand “gotchas” (common mistakes) were moved from chapter ends to part ends—they now appear at the end of the last chapter in each part
com-In this third edition, I’ve also augmented the end-of-part exercises with end-of-chaptersummaries and end-of-chapter quizzes to help you review chapters as you completethem Each chapter concludes with a set of questions to help you review and test yourunderstanding of the chapter’s material Unlike the end-of-part exercises, whosesolutions are presented in Appendix B, the solutions to the end-of-chapter quizzesappear immediately after the questions; I encourage you to look at the solutions even
if you’re sure you’ve answered the questions correctly because the answers are a sort
of review in themselves
Despite all the new topics, this book is still oriented toward Python newcomers, and
is designed to be a first Python text for programmers.*It retains much of the first twoeditions’ material, structure, and focus Where appropriate, I’ve expanded introduc-tions for newcomers, and isolated the more advanced new topics from the mainthread of discussion to avoid obscuring the fundamentals Moreover, because it islargely based on time-tested training experience and materials, this edition, like thefirst two, can still serve as a self-paced introductory Python class
* And by “programmers,” I mean anyone who has written a single line of code in any programming or ing language in the past If this doesn’t include you, you will probably find this book useful anyhow, but be aware that it will spend more time teaching Python than programming fundamentals.
Trang 33script-This Edition’s Scope Changes
This third edition is intended as a tutorial on the core Python language, and nothingelse It’s about learning the language in an in-depth fashion, before applying it inapplication-level programming The presentation here is bottom-up and gradual, but
it provides a complete look at the entire language, in isolation from its applicationroles
For some, “learning Python” involves spending an hour or two going through a rial on the Web This works for already advanced programmers up to a point;Python is, after all, relatively simple by comparison to other languages The problemwith this fast-track approach is that its practitioners eventually stumble onto unusualcases and get stuck—variables change out from under them, mutable default argu-ments mutate inexplicably, and so on The goal here is instead to provide a solidgrounding in Python fundamentals, so that even the unusual cases will make sensewhen they crop up
tuto-This scope is deliberate By restricting our gaze to language fundamentals, we caninvestigate them here in more satisfying depth Other texts, such as O’Reilly’s
Programming Python, Python Cookbook, Python in a Nutshell, and Python Pocket Reference, pick up where this book leaves off and provide a more complete look at
application-level topics and reference materials The purpose of the book you arereading now is solely to teach Python itself so that you can apply it to whateverdomain you happen to work in
Because of that focus change, some of the prior edition’s reference and moreadvanced sections (that is, roughly 15 percent of the prior edition) have been cut toexpand the core language sections In exchange, readers of this edition will find amore thorough look at the core language, and a more useful first Python book Ahandful of more advanced examples were also added as self-study programs as thefinal exercise in this edition (see Chapter 29)
About This Book
This section underscores some important points about this book in general, regardless
of its edition number No book addresses every possible audience, so it’s important tounderstand a book’s goals up front
This Book’s Prerequisites
There are no absolute prerequisites to speak of, really Both true beginners andcrusty programming veterans have used this book successfully If you are motivated
to learn Python, this text will probably work for you In general, though, I havefound that any exposure to programming or scripting before this book can be help-ful, even if not required for every reader
Trang 34This book is designed to be an introductory-level Python text for programmers Itmay not be an ideal text for someone who has never touched a computer before (forinstance, we’re not going to spend any time exploring what a computer is), but Ihaven’t made many assumptions about your programming background or education.
On the other hand, I won’t insult readers by assuming they are “dummies” either,whatever that means—it’s easy to do useful things in Python, and this book willshow you how The text occasionally contrasts Python with languages such as C,C++, Java™, and Pascal, but you can safely ignore these comparisons if you haven’tused such languages in the past
This Book’s Scope and Other Books
Although this book covers all the essentials of the Python language, I’ve kept itsscope narrow in the interests of speed and size To keep things simple, this bookfocuses on core concepts, uses small and self-contained examples to illustrate points,and sometimes omits the small details that are readily available in reference manu-als Because of that, this book is probably best described as an introduction and astepping-stone to more advanced and complete texts
For example, we won’t talk much about Python/C integration—a complex topic that
is nevertheless central to many Python-based systems We also won’t talk muchabout Python’s history or development processes And popular Python applicationssuch as GUIs, system tools, and network scripting get only a short glance, if they arementioned at all Naturally, this scope misses some of the big picture
By and large, Python is about raising the quality bar a few notches in the scriptingworld Some of its ideas require more context than can be provided here, and I’d beremiss if I didn’t recommend further study after you finish this book I hope thatmost readers of this book will eventually go on to gain a more complete understand-ing of application-level programming from other texts
Because of its beginner’s focus, Learning Python is designed to be naturally mented by O’Reilly’s other Python books For instance, Programming Python,
comple-another book I authored, provides larger and more complete examples, along withtutorials on application programming techniques, and was explicitly designed to be afollow-up text to the one you are reading now Roughly, the current editions of
Learning Python and Programming Python reflect the two halves of their author’s
training materials—the core language, and application programming In addition,
O’Reilly’s Python Pocket Reference serves as a quick reference supplement for
look-ing up some of the finer details skipped here
Other follow-up books can also provide references, additional examples, or detailsabout using Python in specific domains such as the Web and GUIs For instance,
O’Reilly’s Python in a Nutshell and Sams’s Python Essential Reference provide ences, and O’Reilly’s Python Cookbook offers a library of self-contained examples for
Trang 35refer-people already familiar with application programming techniques Because books aresuch a subjective experience, I encourage you to browse on your own to findadvanced texts that suit your needs Regardless of which books you choose, though,keep in mind that the rest of the Python story requires studying examples that aremore realistic than there is space for here.
Having said that, I think you’ll find this book to be a good first text on Python,despite its limited scope (and perhaps because of it) You’ll learn everything you need
to get started writing useful standalone Python programs and scripts By the timeyou’ve finished this book, you will have learned not only the language itself, but alsohow to apply it well to your day-to-day tasks And, you’ll be equipped to tackle moreadvanced topics and examples as they come your way
This Book’s Style and Structure
This book is based on training materials developed for a three-day hands-on Pythoncourse You’ll find end-of-chapter quizzes at the end of each chapter, and end-of-partexercises at the end of the last chapter of each part Solutions to chapter quizzesappear in the chapters themselves, and solutions to part exercises show up inAppendix B The quizzes are designed to review material, while the exercises aredesigned to get you coding right away and are usually one of the highlights of thecourse
I strongly recommend working through the quizzes and exercises along the way, notonly to gain Python programming experience, but also because some of the exercisesraise issues not covered elsewhere in the book The solutions in the chapters and inAppendix B should help you if you get stuck (and you are encouraged to peek at theanswers as much and as often as you like)
The overall structure of this book is also derived from class materials Because thistext is designed to introduce language basics quickly, I’ve organized the presentation
by major language features, not examples We’ll take a bottom-up approach here:from built-in object types, to statements, to program units, and so on Each chapter
is fairly self-contained, but later chapters draw upon ideas introduced in earlier ones(e.g., by the time we get to classes, I’ll assume you know how to write functions), so
a linear reading makes the most sense for most readers
In general terms, this book presents the Python language in a bottom-up fashion It isorganized with one part per major language feature—types, functions, and soforth—and most of the examples are small and self-contained (some might also callthe examples in this text artificial, but they illustrate the points it aims to make).More specifically, here is what you will find:
Trang 36Part I, Getting Started
We begin with a general overview of Python that answers commonly asked tial questions—why people use the language, what it’s useful for, and so on Thefirst chapter introduces the major ideas underlying the technology to give yousome background context Then the technical material of the book begins, as weexplore the ways that both we and Python run programs The goal of this part ofthe book is to give you just enough information to be able to follow along withlater examples and exercises
ini-Part II, Types and Operations
Next, we begin our tour of the Python language, studying Python’s major
built-in object types built-in depth: numbers, lists, dictionaries, and so on You can get a lotdone in Python with these tools alone This is the most substantial part of thebook because we lay groundwork here for later chapters We’ll also look atdynamic typing and its references—keys to using Python well—in this part
Part III, Statements and Syntax
The next part moves on to introduce Python’s statements—the code you type to
create and process objects in Python It also presents Python’s general syntaxmodel Although this part focuses on syntax, it also introduces some relatedtools, such as the PyDoc system, and explores coding alternatives
Part IV, Functions
This part begins our look at Python’s higher-level program structure tools tions turn out to be a simple way to package code for reuse and avoid coderedundancy In this part, we will explore Python’s scoping rules, argument-passing techniques, and more
Func-Part V, Modules
Python modules let you organize statements and functions into larger nents, and this part illustrates how to create, use, and reload modules We’ll alsolook at some more advanced topics here, such as module packages, modulereloading, and the_ _name_ _ variable
compo-Part VI, Classes and OOP
Here, we explore Python’s object-oriented programming (OOP) tool, the class—
an optional but powerful way to structure code for customization and reuse Asyou’ll see, classes mostly reuse ideas we will have covered by this point in thebook, and OOP in Python is mostly about looking up names in linked objects
As you’ll also see, OOP is optional in Python, but can shave development timesubstantially, especially for long-term strategic project development
Part VII, Exceptions and Tools
We wrap up the text with a look at Python’s exception handling model andstatements, plus a brief overview of development tools that will become moreuseful when you start writing larger programs (debugging and testing tools, forinstance) This part comes last, exceptions should now all be classes
Trang 37Part VIII, Appendixes
The book ends with a pair of appendixes that give platform-specific tips forusing Python on various computers (Appendix A) and provide solutions to theend-of-part exercises (Appendix B) Solutions to end-of-chapter quizzes appear
in the chapters themselves
Note that the index and table of contents can be used to hunt for details, but thereare no reference appendixes in this book (this book is a tutorial, not a reference) As
mentioned earlier, you can consult the Python Pocket Reference (O’Reilly), as well as other books, and the free Python reference manuals maintained at http://www.
python.org, for syntax and built-in tool details.
Book Updates
Improvements happen (and so do mis^H^H^Htypos) Updates, supplements, and rections for this book will be maintained (or referenced) on the Web at one of thefollowing sites:
cor-http://www.oreilly.com/catalog/9780596513986/ (O’Reilly’s web page for the book) http://www.rmi.net/~lutz (the author’s site)
http://www.rmi.net/~lutz/about-lp.html (the author’s web page for the book)
The last of these three URLs points to a web page for this book where I will postupdates, but be sure to search the Web if this link becomes invalid If I could bemore clairvoyant, I would, but the Web changes faster than printed books
About the Programs in This Book
This book, and all the program examples in it, is based on Python version 2.5 Inaddition, although I won’t try to predict the future, discussion of some ideas in theanticipated 3.0 release are mixed in along the way
Because this text focuses on the core language, however, you can be fairly sure thatmost of what it has to say won’t change very much in future releases of Python Most
of this book applies to earlier Python versions, too, except when it does not; rally, if you try using extensions added after the release you’ve got, all bets are off
natu-As a rule of thumb, the latest Python is the best Python Because this book focuses onthe core language, most of it also applies to Jython, the Java-based Python languageimplementation, as well other Python implementations described in Chapter 2.Source code for the book’s examples, as well as exercise solutions, can be fetched
from the book’s web site at http://www.oreilly.com/catalog/9780596513986/ So how
do you run the examples? We’ll study startup details in Chapter 3, so please staytuned for details on this front
Trang 38Preparing for Python 3.0
The first alpha release of Python 3.0 came out just before this book went to theprinter, and after it had been written Officially speaking, this edition of this book isbased on the Python 2.x line (specifically, version 2.5), but it has been augmentedwith numerous notes about anticipated changes in the upcoming Python 3.0 release.Version 3.0 won’t be officially released until roughly one year after this book hasbeen published, and it isn’t expected to be in wide use for at least two years Never-theless, if you’ve picked up this book after 3.0 is in common use, this sectionprovides a brief description of some of the changes in the language you will likelyencounter to help you make the transition
Although there are a few notable exceptions, most of the Python language in version3.0 will be the same as described in this book, and the impact on typical and practi-cal applications code will be minor That is, the fundamentals of Python presented inthis book will not change from release to release, and readers will benefit by study-ing those fundamentals here first before dealing with release-specific details
To help you retarget code in the future, though, the following list highlights themajor differences in Python 3.0 Pointers to the chapters in this edition that eitherdiscuss or are impacted by these changes are noted as well, and the list is ordered byrelevant chapter number Some of these changes can be coded today in Python 2.5, andsome cannot Because much of the following list won’t make sense to most readers atthis point, I suggest you first study this book at large to learn the fundamentals ofPython, and return to this list later to see the changes in 3.0 In Python 3.0:
• The current execfile() built-in function is removed; use exec() instead (seeChapter 3)
• Thereload()built-in functions may be removed; an alternative is not yet known(see Chapters 3 and 19)
• The 'X'backquotes string conversion expression is removed: use repr(X) (seeChapter 5)
• TheX<> Y redundant inequality expression is removed: useX!= Y (see Chapter 5)
• Sets can be created with new literal syntax{1, 3, 2} equivalent to the current
set([1, 3, 2]) (see Chapter 5)
• Set comprehensions may be coded:{f(x) for x in S if P(x)}, which is the same
as the current generator expression:set(f(x) for x in S if P(x)) (see Chapter 5)
• True division is turned on: X / Y always returns a floating-point number thatretains the remainder, even for integers; useX// Yto invoke today’s truncatingdivision (see Chapter 5)
• There is only one integer type,int, which supports the arbitrary precision of thecurrentlong type (see Chapter 5)
Trang 39• Octal and binary literals: the current octal 0666 becomes an error: use 0o666
instead, and the oct() function’s result has been changed accordingly; 0b1010
now equals 10, andbin(10) returns"0b1010" (see Chapter 5)
• The string typestrsupports wide-character Unicode text, and a newbytestyperepresents short-character strings (e.g, when loaded from files in binary mode);
bytes is a mutable sequence of small integers with a slightly different interfacethanstr (see Chapter 7)
• There is a new, optional technique for string formatting: "See {0}, {1} and {foo}".format("A", "B", foo="C") makes"See A, B and C" (see Chapter 7)
• The dictionaryD.has_key(X) method will be removed; use Xin D membershipinstead (see Chapters 4 and 8)
• Comparisons (and by proxy, sorts) of mixed non-numeric types raise exceptionsinstead of using the current arbitrary but fixed cross-type ordering (see Chapters
8 and 9)
• Dictionary methods .keys(), .items() and .values() will return iterable-like
“view” objects, instead of lists; use list() to force a list to be built if needed (seeChapter 8)
• Because of the prior point, this coding pattern no longer works:k = D.keys(); k.sort(); usek = sorted(D) instead (see Chapters 4 and 8)
• Thefile() built-in function may be removed; useopen() instead (see Chapter 9)
• Theraw_input()built-in function will be renamedinput(); useeval(input())toget the behavior of today’sinput() function (see Chapter 10)
• The exec code-string execution statement becomes a built-in function again(Chapter 10)
• as,with, andnonlocal become new reserved words;execno longer is reservedbecause of the prior point (see Chapter 11)
• Printing is a function to support more features, not a statement: useprint(x, y),not print x, y, and use the new function’s keyword arguments to customizeprinting behavior:file=sys.stdout, sep=" ", andend="\n" (see Chapter 11)
• Extended iterable unpacking: statement that supports generalized sequenceassignment such as a, b, *rest = some_sequencenow work, as does *rest, a = stuff; thus, the number of items on the left and right of an assignment state-ment no longer must match (see Chapter 11)
• Automatic tuple parameter unpacking via sequence assignment is removed forfunctions; you can no longer writedef foo(a, (b, c)):, and must usedef foo(a, bc): b, c = bc to perform sequence assignment explicitly instead (see Chapter 11)
• The currentxrange() built-in function is renamed torange(); that is, there isonlyrange() (see Chapter 13)
Trang 40• In the iterator protocol, theX.next()method is renamed toX. next (), and anew built-in function,next(X), calls theX. next ()method on an object (seeChapters 13 and 17).
• The built-in functionszip(),map(), andfilter()return iterators; uselist()toforce construction of a list of results (see Chapters 13 and 17)
• Functions may optionally include annotations describing arguments and results:
def foo(x: "spam", y: list(range(3))) -> 42*2:, which are simply attached to thefunction object’s foo.func_annotations dictionary attribute at runtime: {'x':
"spam", 'y': [0, 1, 2], "return": 84} (see Chapter 15)
• The newnonlocal x, y statement allows write access to variables in enclosingfunction scopes (see Chapter 16)
• The apply(func, args, kws) function will be removed; use the func(*args,
**kws) call syntax instead (see Chapters 16 and 17)
• Thereduce() built-in function is removed; code a loop like that shown in thisbook instead;lambda,map(), andfilter() are retained in 3.0 (see Chapter 17)
• All imports become absolute by default, and skip a package’s own directory: usethe new syntax from import name to invoke today’s relative imports instead(see Chapter 21)
• All classes will be new style classes, and will support today’s new style sions (see Chapter 26)
exten-• Theclass Spam(object) derivation required today for new style classes will not
be required for classes; in 3.0, both today’s standalone “classic” and derived
“new-style” classes are automatically considered what is called new-style today(see Chapter 26)
• In atrystatement, the formexcept namevalue becomesexcept nameasvalue(seeChapter 27)
• In araisestatement,raise E, Vmust be coded asraise E(V)to make an instanceexplicitly (see Chapter 27)
• Thewith/asexceptions context manager feature described in this book is turned
• The package structure of the standard library may be reorganized substantially(see Python 3.0 release notes)