Python 2.3 有什麼新功能¶
- 作者:
A.M. Kuchling
This article explains the new features in Python 2.3. Python 2.3 was releasedon July 29, 2003.
The main themes for Python 2.3 are polishing some of the features added in 2.2,adding various small but useful enhancements to the core language, and expandingthe standard library. The new object model introduced in the previous versionhas benefited from 18 months of bugfixes and from optimization efforts that haveimproved the performance of new-style classes. A few new built-in functionshave been added such assum()
andenumerate()
. Thein
operator can now be used for substring searches (e.g."ab"in"abc"
returnsTrue
).
Some of the many new library features include Boolean, set, heap, and date/timedata types, the ability to import modules from ZIP-format archives, metadatasupport for the long-awaited Python catalog, an updated version of IDLE, andmodules for logging messages, wrapping text, parsing CSV files, processingcommand-line options, using BerkeleyDB databases... the list of new andenhanced modules is lengthy.
This article doesn't attempt to provide a complete specification of the newfeatures, but instead provides a convenient overview. For full details, youshould refer to the documentation for Python 2.3, such as the Python LibraryReference and the Python Reference Manual. If you want to understand thecomplete implementation and design rationale, refer to the PEP for a particularnew feature.
PEP 218: A Standard Set Datatype¶
The newsets
module contains an implementation of a set datatype. TheSet
class is for mutable sets, sets that can have members added andremoved. TheImmutableSet
class is for sets that can't be modified,and instances ofImmutableSet
can therefore be used as dictionary keys.Sets are built on top of dictionaries, so the elements within a set must behashable.
以下是個簡單範例:
>>>importsets>>>S=sets.Set([1,2,3])>>>SSet([1, 2, 3])>>>1inSTrue>>>0inSFalse>>>S.add(5)>>>S.remove(3)>>>SSet([1, 2, 5])>>>
The union and intersection of sets can be computed with theunion()
andintersection()
methods; an alternative notation uses the bitwise operators&
and|
. Mutable sets also have in-place versions of these methods,union_update()
andintersection_update()
.
>>>S1=sets.Set([1,2,3])>>>S2=sets.Set([4,5,6])>>>S1.union(S2)Set([1, 2, 3, 4, 5, 6])>>>S1|S2# Alternative notationSet([1, 2, 3, 4, 5, 6])>>>S1.intersection(S2)Set([])>>>S1&S2# Alternative notationSet([])>>>S1.union_update(S2)>>>S1Set([1, 2, 3, 4, 5, 6])>>>
It's also possible to take the symmetric difference of two sets. This is theset of all elements in the union that aren't in the intersection. Another wayof putting it is that the symmetric difference contains all elements that are inexactly one set. Again, there's an alternative notation (^
), and anin-place version with the ungainly namesymmetric_difference_update()
.
>>>S1=sets.Set([1,2,3,4])>>>S2=sets.Set([3,4,5,6])>>>S1.symmetric_difference(S2)Set([1, 2, 5, 6])>>>S1^S2Set([1, 2, 5, 6])>>>
There are alsoissubset()
andissuperset()
methods for checkingwhether one set is a subset or superset of another:
>>>S1=sets.Set([1,2,3])>>>S2=sets.Set([2,3])>>>S2.issubset(S1)True>>>S1.issubset(S2)False>>>S1.issuperset(S2)True>>>
也參考
- PEP 218 - Adding a Built-In Set Object Type
PEP written by Greg V. Wilson. Implemented by Greg V. Wilson, Alex Martelli, andGvR.
PEP 255:簡單產生器¶
In Python 2.2, generators were added as an optional feature, to be enabled by afrom__future__importgenerators
directive. In 2.3 generators no longerneed to be specially enabled, and are now always present; this means thatyield
is now always a keyword. The rest of this section is a copy ofthe description of generators from the "What's New in Python 2.2" document; ifyou read it back when Python 2.2 came out, you can skip the rest of thissection.
You're doubtless familiar with how function calls work in Python or C. When youcall a function, it gets a private namespace where its local variables arecreated. When the function reaches areturn
statement, the localvariables are destroyed and the resulting value is returned to the caller. Alater call to the same function will get a fresh new set of local variables.But, what if the local variables weren't thrown away on exiting a function?What if you could later resume the function where it left off? This is whatgenerators provide; they can be thought of as resumable functions.
以下是產生器函式最簡單的範例:
defgenerate_ints(N):foriinrange(N):yieldi
A new keyword,yield
, was introduced for generators. Any functioncontaining ayield
statement is a generator function; this isdetected by Python's bytecode compiler which compiles the function specially asa result.
When you call a generator function, it doesn't return a single value; instead itreturns a generator object that supports the iterator protocol. On executingtheyield
statement, the generator outputs the value ofi
,similar to areturn
statement. The big difference betweenyield
and areturn
statement is that on reaching ayield
the generator's state of execution is suspended and localvariables are preserved. On the next call to the generator's.next()
method, the function will resume executing immediately after theyield
statement. (For complicated reasons, theyield
statement isn't allowed inside thetry
block of atry
...finally
statement; readPEP 255 for a fullexplanation of the interaction betweenyield
and exceptions.)
Here's a sample usage of thegenerate_ints()
generator:
>>>gen=generate_ints(3)>>>gen<generator object at 0x8117f90>>>>gen.next()0>>>gen.next()1>>>gen.next()2>>>gen.next()Traceback (most recent call last): File"stdin", line1, in? File"stdin", line2, ingenerate_intsStopIteration
You could equally writeforiingenerate_ints(5)
, ora,b,c=generate_ints(3)
.
Inside a generator function, thereturn
statement can only be usedwithout a value, and signals the end of the procession of values; afterwards thegenerator cannot return any further values.return
with a value, suchasreturn5
, is a syntax error inside a generator function. The end of thegenerator's results can also be indicated by raisingStopIteration
manually, or by just letting the flow of execution fall off the bottom of thefunction.
You could achieve the effect of generators manually by writing your own classand storing all the local variables of the generator as instance variables. Forexample, returning a list of integers could be done by settingself.count
to0, and having thenext()
method incrementself.count
and return it.However, for a moderately complicated generator, writing a corresponding classwould be much messier.Lib/test/test_generators.py
contains a number ofmore interesting examples. The simplest one implements an in-order traversal ofa tree using generators recursively.
# A recursive generator that generates Tree leaves in in-order.definorder(t):ift:forxininorder(t.left):yieldxyieldt.labelforxininorder(t.right):yieldx
Two other examples inLib/test/test_generators.py
produce solutions forthe N-Queens problem (placing $N$ queens on an $NxN$ chess board so that noqueen threatens another) and the Knight's Tour (a route that takes a knight toevery square of an $NxN$ chessboard without visiting any square twice).
The idea of generators comes from other programming languages, especially Icon(https://www2.cs.arizona.edu/icon/), where the idea of generators is central. InIcon, every expression and function call behaves like a generator. One examplefrom "An Overview of the Icon Programming Language" athttps://www2.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this lookslike:
sentence:="Store it in the neighboring harbor"if(i:=find("or",sentence))>5thenwrite(i)
In Icon thefind()
function returns the indexes at which the substring"or" is found: 3, 23, 33. In theif
statement,i
is firstassigned a value of 3, but 3 is less than 5, so the comparison fails, and Iconretries it with the second value of 23. 23 is greater than 5, so the comparisonnow succeeds, and the code prints the value 23 to the screen.
Python doesn't go nearly as far as Icon in adopting generators as a centralconcept. Generators are considered part of the core Python language, butlearning or using them isn't compulsory; if they don't solve any problems thatyou have, feel free to ignore them. One novel feature of Python's interface ascompared to Icon's is that a generator's state is represented as a concreteobject (the iterator) that can be passed around to other functions or stored ina data structure.
也參考
- PEP 255 - 簡單產生器
Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland. Implemented mostlyby Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.
PEP 263: Source Code Encodings¶
Python source files can now be declared as being in different character setencodings. Encodings are declared by including a specially formatted comment inthe first or second line of the source file. For example, a UTF-8 file can bedeclared with:
#!/usr/bin/env python# -*- coding: UTF-8 -*-
Without such an encoding declaration, the default encoding used is 7-bit ASCII.Executing or importing modules that contain string literals with 8-bitcharacters and have no encoding declaration will result in aDeprecationWarning
being signalled by Python 2.3; in 2.4 this will be asyntax error.
The encoding declaration only affects Unicode string literals, which will beconverted to Unicode using the specified encoding. Note that Python identifiersare still restricted to ASCII characters, so you can't have variable names thatuse characters outside of the usual alphanumerics.
也參考
- PEP 263 - Defining Python Source Code Encodings
Written by Marc-André Lemburg and Martin von Löwis; implemented by Suzuki Hisaoand Martin von Löwis.
PEP 273: Importing Modules from ZIP Archives¶
The newzipimport
module adds support for importing modules from aZIP-format archive. You don't need to import the module explicitly; it will beautomatically imported if a ZIP archive's filename is added tosys.path
.For example:
amk@nyman:~/src/python$unzip-l/tmp/example.zipArchive: /tmp/example.zip Length Date Time Name -------- ---- ---- ---- 8467 11-26-02 22:30 jwzthreading.py -------- ------- 8467 1 fileamk@nyman:~/src/python$./pythonPython 2.3 (#1, Aug 1 2003, 19:54:32)>>> import sys>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path>>> import jwzthreading>>> jwzthreading.__file__'/tmp/example.zip/jwzthreading.py'>>>
An entry insys.path
can now be the filename of a ZIP archive. The ZIParchive can contain any kind of files, but only files named*.py
,*.pyc
, or*.pyo
can be imported. If an archive only contains*.py
files, Python will not attempt to modify the archive by adding thecorresponding*.pyc
file, meaning that if a ZIP archive doesn't contain*.pyc
files, importing may be rather slow.
A path within the archive can also be specified to only import from asubdirectory; for example, the path/tmp/example.zip/lib/
would onlyimport from thelib/
subdirectory within the archive.
也參考
- PEP 273 - Import Modules from Zip Archives
Written by James C. Ahlstrom, who also provided an implementation. Python 2.3follows the specification inPEP 273, but uses an implementation written byJust van Rossum that uses the import hooks described inPEP 302. See sectionPEP 302: New Import Hooks for a description of the new import hooks.
PEP 277: Unicode file name support for Windows NT¶
On Windows NT, 2000, and XP, the system stores file names as Unicode strings.Traditionally, Python has represented file names as byte strings, which isinadequate because it renders some file names inaccessible.
Python now allows using arbitrary Unicode strings (within the limitations of thefile system) for all functions that expect file names, most notably theopen()
built-in function. If a Unicode string is passed toos.listdir()
, Python now returns a list of Unicode strings. A newfunction,os.getcwdu()
, returns the current directory as a Unicode string.
Byte strings still work as file names, and on Windows Python will transparentlyconvert them to Unicode using thembcs
encoding.
Other systems also allow Unicode strings as file names but convert them to bytestrings before passing them to the system, which can cause aUnicodeError
to be raised. Applications can test whether arbitrary Unicode strings aresupported as file names by checkingos.path.supports_unicode_filenames
,a Boolean value.
Under MacOS,os.listdir()
may now return Unicode filenames.
也參考
- PEP 277 - Unicode file name support for Windows NT
Written by Neil Hodgson; implemented by Neil Hodgson, Martin von Löwis, and MarkHammond.
PEP 278: Universal Newline Support¶
The three major operating systems used today are Microsoft Windows, Apple'sMacintosh OS, and the various Unix derivatives. A minor irritation ofcross-platform work is that these three platforms all use different characters tomark the ends of lines in text files. Unix uses the linefeed (ASCII character10), MacOS uses the carriage return (ASCII character 13), and Windows uses atwo-character sequence of a carriage return plus a newline.
Python's file objects can now support end of line conventions other than theone followed by the platform on which Python is running. Opening a file withthe mode'U'
or'rU'
will open a file for reading inuniversalnewlines mode. All three line ending conventions will be translated to a'\n'
in the strings returned by the various file methods such asread()
andreadline()
.
Universal newline support is also used when importing modules and when executinga file with theexecfile()
function. This means that Python modules canbe shared between all three operating systems without needing to convert theline-endings.
This feature can be disabled when compiling Python by specifying the--without-universal-newlines
switch when running Python'sconfigure script.
也參考
- PEP 278 - Universal Newline Support
Written and implemented by Jack Jansen.
PEP 279:enumerate()¶
A new built-in function,enumerate()
, will make certain loops a bitclearer.enumerate(thing)
, wherething is either an iterator or asequence, returns an iterator that will return(0,thing[0])
,(1,thing[1])
,(2,thing[2])
, and so forth.
A common idiom to change every element of a list looks like this:
foriinrange(len(L)):item=L[i]# ... compute some result based on item ...L[i]=result
This can be rewritten usingenumerate()
as:
fori,iteminenumerate(L):# ... compute some result based on item ...L[i]=result
也參考
- PEP 279 - The enumerate() built-in function
Written and implemented by Raymond D. Hettinger.
PEP 282: The logging Package¶
A standard package for writing logs,logging
, has been added to Python2.3. It provides a powerful and flexible mechanism for generating loggingoutput which can then be filtered and processed in various ways. Aconfiguration file written in a standard format can be used to control thelogging behavior of a program. Python includes handlers that will write logrecords to standard error or to a file or socket, send them to the system log,or even e-mail them to a particular address; of course, it's also possible towrite your own handler classes.
TheLogger
class is the primary class. Most application code will dealwith one or moreLogger
objects, each one used by a particularsubsystem of the application. EachLogger
is identified by a name, andnames are organized into a hierarchy using.
as the component separator.For example, you might haveLogger
instances namedserver
,server.auth
andserver.network
. The latter two instances are belowserver
in the hierarchy. This means that if you turn up the verbosity forserver
or directserver
messages to a different handler, the changeswill also apply to records logged toserver.auth
andserver.network
.There's also a rootLogger
that's the parent of all other loggers.
For simple uses, thelogging
package contains some convenience functionsthat always use the root log:
importlogginglogging.debug('Debugging information')logging.info('Informational message')logging.warning('Warning:config file%s not found','server.conf')logging.error('Error occurred')logging.critical('Critical error -- shutting down')
This produces the following output:
WARNING:root:Warning:configfileserver.confnotfoundERROR:root:ErroroccurredCRITICAL:root:Criticalerror--shuttingdown
In the default configuration, informational and debugging messages aresuppressed and the output is sent to standard error. You can enable the displayof informational and debugging messages by calling thesetLevel()
methodon the root logger.
Notice thewarning()
call's use of string formatting operators; all of thefunctions for logging messages take the arguments(msg,arg1,arg2,...)
andlog the string resulting frommsg%(arg1,arg2,...)
.
There's also anexception()
function that records the most recenttraceback. Any of the other functions will also record the traceback if youspecify a true value for the keyword argumentexc_info.
deff():try:1/0except:logging.exception('Problem recorded')f()
This produces the following output:
ERROR:root:ProblemrecordedTraceback(mostrecentcalllast):File"t.py",line6,inf1/0ZeroDivisionError:integerdivisionormodulobyzero
Slightly more advanced programs will use a logger other than the root logger.ThegetLogger(name)
function is used to get a particular log, creatingit if it doesn't exist yet.getLogger(None)
returns the root logger.
log=logging.getLogger('server')...log.info('Listening on port%i',port)...log.critical('Disk full')...
Log records are usually propagated up the hierarchy, so a message logged toserver.auth
is also seen byserver
androot
, but aLogger
can prevent this by setting itspropagate
attribute toFalse
.
There are more classes provided by thelogging
package that can becustomized. When aLogger
instance is told to log a message, itcreates aLogRecord
instance that is sent to any number of differentHandler
instances. Loggers and handlers can also have an attached listof filters, and each filter can cause theLogRecord
to be ignored orcan modify the record before passing it along. When they're finally output,LogRecord
instances are converted to text by aFormatter
class. All of these classes can be replaced by your own specially writtenclasses.
With all of these features thelogging
package should provide enoughflexibility for even the most complicated applications. This is only anincomplete overview of its features, so please see the package's referencedocumentation for all of the details. ReadingPEP 282 will also be helpful.
也參考
- PEP 282 - A Logging System
Written by Vinay Sajip and Trent Mick; implemented by Vinay Sajip.
PEP 285: A Boolean Type¶
A Boolean type was added to Python 2.3. Two new constants were added to the__builtin__
module,True
andFalse
. (True
andFalse
constants were added to the built-ins in Python 2.2.1, but the2.2.1 versions are simply set to integer values of 1 and 0 and aren't adifferent type.)
The type object for this new type is namedbool
; the constructor for ittakes any Python value and converts it toTrue
orFalse
.
>>>bool(1)True>>>bool(0)False>>>bool([])False>>>bool((1,))True
Most of the standard library modules and built-in functions have been changed toreturn Booleans.
>>>obj=[]>>>hasattr(obj,'append')True>>>isinstance(obj,list)True>>>isinstance(obj,tuple)False
Python's Booleans were added with the primary goal of making code clearer. Forexample, if you're reading a function and encounter the statementreturn1
,you might wonder whether the1
represents a Boolean truth value, an index,or a coefficient that multiplies some other quantity. If the statement isreturnTrue
, however, the meaning of the return value is quite clear.
Python's Booleans werenot added for the sake of strict type-checking. A verystrict language such as Pascal would also prevent you performing arithmetic withBooleans, and would require that the expression in anif
statementalways evaluate to a Boolean result. Python is not this strict and never willbe, asPEP 285 explicitly says. This means you can still use any expressionin anif
statement, even ones that evaluate to a list or tuple orsome random object. The Boolean type is a subclass of theint
class sothat arithmetic using a Boolean still works.
>>>True+12>>>False+11>>>False*750>>>True*7575
To sum upTrue
andFalse
in a sentence: they're alternativeways to spell the integer values 1 and 0, with the single difference thatstr()
andrepr()
return the strings'True'
and'False'
instead of'1'
and'0'
.
也參考
- PEP 285 - Adding a bool type
Written and implemented by GvR.
PEP 293: Codec Error Handling Callbacks¶
When encoding a Unicode string into a byte string, unencodable characters may beencountered. So far, Python has allowed specifying the error processing aseither "strict" (raisingUnicodeError
), "ignore" (skipping thecharacter), or "replace" (using a question mark in the output string), with"strict" being the default behavior. It may be desirable to specify alternativeprocessing of such errors, such as inserting an XML character reference or HTMLentity reference into the converted string.
Python now has a flexible framework to add different processing strategies. Newerror handlers can be added withcodecs.register_error()
, and codecs thencan access the error handler withcodecs.lookup_error()
. An equivalent CAPI has been added for codecs written in C. The error handler gets the necessarystate information such as the string being converted, the position in the stringwhere the error was detected, and the target encoding. The handler can theneither raise an exception or return a replacement string.
Two additional error handlers have been implemented using this framework:"backslashreplace" uses Python backslash quoting to represent unencodablecharacters and "xmlcharrefreplace" emits XML character references.
也參考
- PEP 293 - Codec Error Handling Callbacks
Written and implemented by Walter Dörwald.
PEP 301: Package Index and Metadata for Distutils¶
Support for the long-requested Python catalog makes its first appearance in 2.3.
The heart of the catalog is the new Distutilsregister command.Runningpythonsetup.pyregister
will collect the metadata describing apackage, such as its name, version, maintainer, description, &c., and send it toa central catalog server. The resulting catalog is available fromhttps://pypi.org.
To make the catalog a bit more useful, a new optionalclassifiers keywordargument has been added to the Distutilssetup()
function. A list ofTrove-style strings can be supplied to helpclassify the software.
Here's an examplesetup.py
with classifiers, written to be compatiblewith older versions of the Distutils:
fromdistutilsimportcorekw={'name':"Quixote",'version':"0.5.1",'description':"A highly Pythonic Web application framework",# ...}if(hasattr(core,'setup_keywords')and'classifiers'incore.setup_keywords):kw['classifiers']= \['Topic :: Internet :: WWW/HTTP :: Dynamic Content','Environment :: No Input/Output (Daemon)','Intended Audience :: Developers'],core.setup(**kw)
The full list of classifiers can be obtained by runningpythonsetup.pyregister--list-classifiers
.
也參考
- PEP 301 - Package Index and Metadata for Distutils
Written and implemented by Richard Jones.
PEP 302: New Import Hooks¶
While it's been possible to write custom import hooks ever since theihooks
module was introduced in Python 1.3, no one has ever been reallyhappy with it because writing new import hooks is difficult and messy. Therehave been various proposed alternatives such as theimputil
andiu
modules, but none of them has ever gained much acceptance, and none of them wereeasily usable from C code.
PEP 302 borrows ideas from its predecessors, especially from GordonMcMillan'siu
module. Three new items are added to thesys
module:
sys.path_hooks
is a list of callable objects; most often they'll beclasses. Each callable takes a string containing a path and either returns animporter object that will handle imports from this path or raises anImportError
exception if it can't handle this path.sys.path_importer_cache
caches importer objects for each path, sosys.path_hooks
will only need to be traversed once for each path.sys.meta_path
is a list of importer objects that will be traversed beforesys.path
is checked. This list is initially empty, but user code can addobjects to it. Additional built-in and frozen modules can be imported by anobject added to this list.
Importer objects must have a single method,find_module(fullname,path=None)
.fullname will be a module or package name, e.g.string
ordistutils.core
.find_module()
must return a loader object that has asingle method,load_module(fullname)
, that creates and returns thecorresponding module object.
Pseudo-code for Python's new import logic, therefore, looks something like this(simplified a bit; seePEP 302 for the full details):
formpinsys.meta_path:loader=mp(fullname)ifloaderisnotNone:<module>=loader.load_module(fullname)forpathinsys.path:forhookinsys.path_hooks:try:importer=hook(path)exceptImportError:# ImportError, so try the other path hookspasselse:loader=importer.find_module(fullname)<module>=loader.load_module(fullname)# Not found!raiseImportError
也參考
- PEP 302 - New Import Hooks
Written by Just van Rossum and Paul Moore. Implemented by Just van Rossum.
PEP 305: Comma-separated Files¶
Comma-separated files are a format frequently used for exporting data fromdatabases and spreadsheets. Python 2.3 adds a parser for comma-separated files.
Comma-separated format is deceptively simple at first glance:
Costs,150,200,3.95
Read a line and callline.split(',')
: what could be simpler? But toss instring data that can contain commas, and things get more complicated:
"Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"
A big ugly regular expression can parse this, but using the newcsv
package is much simpler:
importcsvinput=open('datafile','rb')reader=csv.reader(input)forlineinreader:printline
Thereader()
function takes a number of different options. The fieldseparator isn't limited to the comma and can be changed to any character, and socan the quoting and line-ending characters.
Different dialects of comma-separated files can be defined and registered;currently there are two dialects, both used by Microsoft Excel. A separatecsv.writer
class will generate comma-separated files from a successionof tuples or lists, quoting strings that contain the delimiter.
也參考
- PEP 305 - CSV 檔案 API
Written and implemented by Kevin Altis, Dave Cole, Andrew McNamara, SkipMontanaro, Cliff Wells.
PEP 307: Pickle Enhancements¶
Thepickle
andcPickle
modules received some attention during the2.3 development cycle. In 2.2, new-style classes could be pickled withoutdifficulty, but they weren't pickled very compactly;PEP 307 quotes a trivialexample where a new-style class results in a pickled string three times longerthan that for a classic class.
The solution was to invent a new pickle protocol. Thepickle.dumps()
function has supported a text-or-binary flag for a long time. In 2.3, thisflag is redefined from a Boolean to an integer: 0 is the old text-mode pickleformat, 1 is the old binary format, and now 2 is a new 2.3-specific format. Anew constant,pickle.HIGHEST_PROTOCOL
, can be used to select thefanciest protocol available.
Unpickling is no longer considered a safe operation. 2.2'spickle
provided hooks for trying to prevent unsafe classes from being unpickled(specifically, a__safe_for_unpickling__
attribute), but none of thiscode was ever audited and therefore it's all been ripped out in 2.3. You shouldnot unpickle untrusted data in any version of Python.
To reduce the pickling overhead for new-style classes, a new interface forcustomizing pickling was added using three special methods:__getstate__()
,__setstate__()
, and__getnewargs__()
. ConsultPEP 307 for the full semantics of these methods.
As a way to compress pickles yet further, it's now possible to use integer codesinstead of long strings to identify pickled classes. The Python SoftwareFoundation will maintain a list of standardized codes; there's also a range ofcodes for private use. Currently no codes have been specified.
也參考
- PEP 307 - Extensions to the pickle protocol
Written and implemented by Guido van Rossum and Tim Peters.
Extended Slices¶
Ever since Python 1.4, the slicing syntax has supported an optional third "step"or "stride" argument. For example, these are all legal Python syntax:L[1:10:2]
,L[:-1:1]
,L[::-1]
. This was added to Python at therequest of the developers of Numerical Python, which uses the third argumentextensively. However, Python's built-in list, tuple, and string sequence typeshave never supported this feature, raising aTypeError
if you tried it.Michael Hudson contributed a patch to fix this shortcoming.
For example, you can now easily extract the elements of a list that have evenindexes:
>>>L=range(10)>>>L[::2][0, 2, 4, 6, 8]
Negative values also work to make a copy of the same list in reverse order:
>>>L[::-1][9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
This also works for tuples, arrays, and strings:
>>>s='abcd'>>>s[::2]'ac'>>>s[::-1]'dcba'
If you have a mutable sequence such as a list or an array you can assign to ordelete an extended slice, but there are some differences between assignment toextended and regular slices. Assignment to a regular slice can be used tochange the length of the sequence:
>>>a=range(3)>>>a[0, 1, 2]>>>a[1:3]=[4,5,6]>>>a[0, 4, 5, 6]
Extended slices aren't this flexible. When assigning to an extended slice, thelist on the right hand side of the statement must contain the same number ofitems as the slice it is replacing:
>>>a=range(4)>>>a[0, 1, 2, 3]>>>a[::2][0, 2]>>>a[::2]=[0,-1]>>>a[0, 1, -1, 3]>>>a[::2]=[0,1,2]Traceback (most recent call last): File"<stdin>", line1, in?ValueError:attempt to assign sequence of size 3 to extended slice of size 2
Deletion is more straightforward:
>>>a=range(4)>>>a[0, 1, 2, 3]>>>a[::2][0, 2]>>>dela[::2]>>>a[1, 3]
One can also now pass slice objects to the__getitem__()
methods of thebuilt-in sequences:
>>>range(10).__getitem__(slice(0,5,2))[0, 2, 4]
Or use slice objects directly in subscripts:
>>>range(10)[slice(0,5,2)][0, 2, 4]
To simplify implementing sequences that support extended slicing, slice objectsnow have a methodindices(length)
which, given the length of a sequence,returns a(start,stop,step)
tuple that can be passed directly torange()
.indices()
handles omitted and out-of-bounds indices in amanner consistent with regular slices (and this innocuous phrase hides a welterof confusing details!). The method is intended to be used like this:
classFakeSeq:...defcalc_item(self,i):...def__getitem__(self,item):ifisinstance(item,slice):indices=item.indices(len(self))returnFakeSeq([self.calc_item(i)foriinrange(*indices)])else:returnself.calc_item(i)
From this example you can also see that the built-inslice
object isnow the type object for the slice type, and is no longer a function. This isconsistent with Python 2.2, whereint
,str
, etc., underwentthe same change.
其他語言更動¶
Here are all of the changes that Python 2.3 makes to the core Python language.
The
yield
statement is now always a keyword, as described insectionPEP 255:簡單產生器 of this document.A new built-in function
enumerate()
was added, as described in sectionPEP 279:enumerate() of this document.Two new constants,
True
andFalse
were added along with thebuilt-inbool
type, as described in sectionPEP 285: A Boolean Type of thisdocument.The
int()
type constructor will now return a long integer instead ofraising anOverflowError
when a string or floating-point number is toolarge to fit into an integer. This can lead to the paradoxical result thatisinstance(int(expression),int)
is false, but that seems unlikely to causeproblems in practice.Built-in types now support the extended slicing syntax, as described insectionExtended Slices of this document.
A new built-in function,
sum(iterable,start=0)
, adds up the numericitems in the iterable object and returns their sum.sum()
only acceptsnumbers, meaning that you can't use it to concatenate a bunch of strings.(Contributed by Alex Martelli.)list.insert(pos,value)
used to insertvalue at the front of the listwhenpos was negative. The behaviour has now been changed to be consistentwith slice indexing, so whenpos is -1 the value will be inserted before thelast element, and so forth.list.index(value)
, which searches forvalue within the list and returnsits index, now takes optionalstart andstop arguments to limit the searchto only part of the list.Dictionaries have a new method,
pop(key[,*default*])
, that returnsthe value corresponding tokey and removes that key/value pair from thedictionary. If the requested key isn't present in the dictionary,default isreturned if it's specified andKeyError
raised if it isn't.>>>d={1:2}>>>d{1: 2}>>>d.pop(4)Traceback (most recent call last): File"stdin", line1, in?KeyError:4>>>d.pop(1)2>>>d.pop(1)Traceback (most recent call last): File"stdin", line1, in?KeyError:'pop(): dictionary is empty'>>>d{}>>>
There's also a new class method,
dict.fromkeys(iterable,value)
, thatcreates a dictionary with keys taken from the supplied iteratoriterable andall values set tovalue, defaulting toNone
.(Patches contributed by Raymond Hettinger.)
Also, the
dict()
constructor now accepts keyword arguments to simplifycreating small dictionaries:>>>dict(red=1,blue=2,green=3,black=4){'blue': 2, 'black': 4, 'green': 3, 'red': 1}
(由 Just van Rossum 所貢獻。)
The
assert
statement no longer checks the__debug__
flag, soyou can no longer disable assertions by assigning to__debug__
. RunningPython with the-O
switch will still generate code that doesn'texecute any assertions.Most type objects are now callable, so you can use them to create new objectssuch as functions, classes, and modules. (This means that the
new
modulecan be deprecated in a future Python version, because you can now use the typeobjects available in thetypes
module.) For example, you can create a newmodule object with the following code:>>>importtypes>>>m=types.ModuleType('abc','docstring')>>>m<module 'abc' (built-in)>>>>m.__doc__'docstring'
A new warning,
PendingDeprecationWarning
was added to indicate featureswhich are in the process of being deprecated. The warning willnot be printedby default. To check for use of features that will be deprecated in the future,supply-Walways::PendingDeprecationWarning::
on the command line orusewarnings.filterwarnings()
.The process of deprecating string-based exceptions, as in
raise"Erroroccurred"
, has begun. Raising a string will now triggerPendingDeprecationWarning
.Using
None
as a variable name will now result in aSyntaxWarning
warning. In a future version of Python,None
may finally become a keyword.The
xreadlines()
method of file objects, introduced in Python 2.1, is nolonger necessary because files now behave as their own iterator.xreadlines()
was originally introduced as a faster way to loop over allthe lines in a file, but now you can simply writeforlineinfile_obj
.File objects also have a new read-onlyencoding
attribute that gives theencoding used by the file; Unicode strings written to the file will beautomatically converted to bytes using the given encoding.The method resolution order used by new-style classes has changed, thoughyou'll only notice the difference if you have a really complicated inheritancehierarchy. Classic classes are unaffected by this change. Python 2.2originally used a topological sort of a class's ancestors, but 2.3 now uses theC3 algorithm as described in the paper"A Monotonic Superclass Linearizationfor Dylan". Tounderstand the motivation for this change, read Michele Simionato's articleThe Python 2.3 Method Resolution Order, orread the thread on python-dev starting with the message athttps://mail.python.org/pipermail/python-dev/2002-October/029035.html. SamuelePedroni first pointed out the problem and also implemented the fix by coding theC3 algorithm.
Python runs multithreaded programs by switching between threads afterexecuting N bytecodes. The default value for N has been increased from 10 to100 bytecodes, speeding up single-threaded applications by reducing theswitching overhead. Some multithreaded applications may suffer slower responsetime, but that's easily fixed by setting the limit back to a lower number using
sys.setcheckinterval(N)
. The limit can be retrieved with the newsys.getcheckinterval()
function.One minor but far-reaching change is that the names of extension types definedby the modules included with Python now contain the module and a
'.'
infront of the type name. For example, in Python 2.2, if you created a socket andprinted its__class__
, you'd get this output:>>>s=socket.socket()>>>s.__class__<type 'socket'>
In 2.3, you get this:
>>>s.__class__<type '_socket.socket'>
One of the noted incompatibilities between old- and new-style classes has beenremoved: you can now assign to the
__name__
and__bases__
attributes of new-style classes. There are some restrictions on what can beassigned to__bases__
along the lines of those relating to assigning toan instance's__class__
attribute.
String Changes¶
The
in
operator now works differently for strings. Previously, whenevaluatingXinY
whereX andY are strings,X could only be a singlecharacter. That's now changed;X can be a string of any length, andXinY
will returnTrue
ifX is a substring ofY. IfX is the emptystring, the result is alwaysTrue
.>>>'ab'in'abcd'True>>>'ad'in'abcd'False>>>''in'abcd'True
Note that this doesn't tell you where the substring starts; if you need thatinformation, use the
find()
string method.The
strip()
,lstrip()
, andrstrip()
string methods now havean optional argument for specifying the characters to strip. The default isstill to remove all whitespace characters:>>>' abc '.strip()'abc'>>>'><><abc<><><>'.strip('<>')'abc'>>>'><><abc<><><>\n'.strip('<>')'abc<><><>\n'>>>u'\u4000\u4001abc\u4000'.strip(u'\u4000')u'\u4001abc'>>>
(Suggested by Simon Brunning and implemented by Walter Dörwald.)
The
startswith()
andendswith()
string methods now accept negativenumbers for thestart andend parameters.Another new string method is
zfill()
, originally a function in thestring
module.zfill()
pads a numeric string with zeros on theleft until it's the specified width. Note that the%
operator is still moreflexible and powerful thanzfill()
.>>>'45'.zfill(4)'0045'>>>'12345'.zfill(4)'12345'>>>'goofy'.zfill(6)'0goofy'
(由 Walter Dörwald 所貢獻。)
A new type object,
basestring
, has been added. Both 8-bit strings andUnicode strings inherit from this type, soisinstance(obj,basestring)
willreturnTrue
for either kind of string. It's a completely abstracttype, so you can't createbasestring
instances.Interned strings are no longer immortal and will now be garbage-collected inthe usual way when the only reference to them is from the internal dictionary ofinterned strings. (Implemented by Oren Tirosh.)
最佳化¶
The creation of new-style class instances has been made much faster; they'renow faster than classic classes!
The
sort()
method of list objects has been extensively rewritten by TimPeters, and the implementation is significantly faster.Multiplication of large long integers is now much faster thanks to animplementation of Karatsuba multiplication, an algorithm that scales better thantheO(n2) required for the grade-school multiplication algorithm. (Originalpatch by Christopher A. Craig, and significantly reworked by Tim Peters.)
The
SET_LINENO
opcode is now gone. This may provide a small speedincrease, depending on your compiler's idiosyncrasies. See sectionOther Changes and Fixes for a longer explanation. (Removed by Michael Hudson.)xrange()
objects now have their own iterator, makingforiinxrange(n)
slightly faster thanforiinrange(n)
. (Patch by RaymondHettinger.)A number of small rearrangements have been made in various hotspots to improveperformance, such as inlining a function or removing some code. (Implementedmostly by GvR, but lots of people have contributed single changes.)
The net result of the 2.3 optimizations is that Python 2.3 runs the pystonebenchmark around 25% faster than Python 2.2.
New, Improved, and Deprecated Modules¶
As usual, Python's standard library received a number of enhancements and bugfixes. Here's a partial list of the most notable changes, sorted alphabeticallyby module name. Consult theMisc/NEWS
file in the source tree for a morecomplete list of changes, or look through the CVS logs for all the details.
The
array
module now supports arrays of Unicode characters using the'u'
format character. Arrays also now support using the+=
assignmentoperator to add another array's contents, and the*=
assignment operator torepeat an array. (Contributed by Jason Orendorff.)The
bsddb
module has been replaced by version 4.1.6 of thePyBSDDB package, providing a more complete interfaceto the transactional features of the BerkeleyDB library.The old version of the module has been renamed to
bsddb185
and is nolonger built automatically; you'll have to editModules/Setup
to enableit. Note that the newbsddb
package is intended to be compatible withthe old module, so be sure to file bugs if you discover any incompatibilities.When upgrading to Python 2.3, if the new interpreter is compiled with a newversion of the underlying BerkeleyDB library, you will almost certainly have toconvert your database files to the new version. You can do this fairly easilywith the new scriptsdb2pickle.py
andpickle2db.py
which youwill find in the distribution'sTools/scripts
directory. If you'vealready been using the PyBSDDB package and importing it asbsddb3
, youwill have to change yourimport
statements to import it asbsddb
.The new
bz2
module is an interface to the bz2 data compression library.bz2-compressed data is usually smaller than correspondingzlib
-compressed data. (Contributed by Gustavo Niemeyer.)A set of standard date/time types has been added in the new
datetime
module. See the following section for more details.The Distutils
Extension
class now supports an extra constructorargument nameddepends for listing additional source files that an extensiondepends on. This lets Distutils recompile the module if any of the dependencyfiles are modified. For example, ifsampmodule.c
includes the headerfilesample.h
, you would create theExtension
object likethis:ext=Extension("samp",sources=["sampmodule.c"],depends=["sample.h"])
Modifying
sample.h
would then cause the module to be recompiled.(Contributed by Jeremy Hylton.)Other minor changes to Distutils: it now checks for the
CC
,CFLAGS
,CPP
,LDFLAGS
, andCPPFLAGS
environment variables, using them to override the settings in Python'sconfiguration (contributed by Robert Weber).Previously the
doctest
module would only search the docstrings ofpublic methods and functions for test cases, but it now also examines privateones as well. TheDocTestSuite()
function creates aunittest.TestSuite
object from a set ofdoctest
tests.The new
gc.get_referents(object)
function returns a list of all theobjects referenced byobject.The
getopt
module gained a new function,gnu_getopt()
, thatsupports the same arguments as the existinggetopt()
function but usesGNU-style scanning mode. The existinggetopt()
stops processing options assoon as a non-option argument is encountered, but in GNU-style mode processingcontinues, meaning that options and arguments can be mixed. For example:>>>getopt.getopt(['-f','filename','output','-v'],'f:v')([('-f', 'filename')], ['output', '-v'])>>>getopt.gnu_getopt(['-f','filename','output','-v'],'f:v')([('-f', 'filename'), ('-v', '')], ['output'])
(由 Peter Åstrand 所貢獻。)
The
grp
,pwd
, andresource
modules now return enhancedtuples:>>>importgrp>>>g=grp.getgrnam('amk')>>>g.gr_name,g.gr_gid('amk', 500)
The
gzip
module can now handle files exceeding 2 GiB.The new
heapq
module contains an implementation of a heap queuealgorithm. A heap is an array-like data structure that keeps items in apartially sorted order such that, for every indexk,heap[k]<=heap[2*k+1]
andheap[k]<=heap[2*k+2]
. This makes it quick to remove thesmallest item, and inserting a new item while maintaining the heap property isO(logn). (Seehttps://xlinux.nist.gov/dads//HTML/priorityque.html for moreinformation about the priority queue data structure.)The
heapq
module providesheappush()
andheappop()
functionsfor adding and removing items while maintaining the heap property on top of someother mutable Python sequence type. Here's an example that uses a Python list:>>>importheapq>>>heap=[]>>>foritemin[3,7,5,11,1]:...heapq.heappush(heap,item)...>>>heap[1, 3, 5, 11, 7]>>>heapq.heappop(heap)1>>>heapq.heappop(heap)3>>>heap[5, 7, 11]
(由 Kevin O'Connor 所貢獻。)
The IDLE integrated development environment has been updated using the codefrom the IDLEfork project (https://idlefork.sourceforge.net). The most notable feature isthat the code being developed is now executed in a subprocess, meaning thatthere's no longer any need for manual
reload()
operations. IDLE's core codehas been incorporated into the standard library as theidlelib
package.The
imaplib
module now supports IMAP over SSL. (Contributed by PiersLauder and Tino Lange.)The
itertools
contains a number of useful functions for use withiterators, inspired by various functions provided by the ML and Haskelllanguages. For example,itertools.ifilter(predicate,iterator)
returns allelements in the iterator for which the functionpredicate()
returnsTrue
, anditertools.repeat(obj,N)
returnsobj
N times.There are a number of other functions in the module; see the package's referencedocumentation for details.(Contributed by Raymond Hettinger.)Two new functions in the
math
module,degrees(rads)
andradians(degs)
, convert between radians and degrees. Other functions inthemath
module such asmath.sin()
andmath.cos()
have alwaysrequired input values measured in radians. Also, an optionalbase argumentwas added tomath.log()
to make it easier to compute logarithms for basesother thane
and10
. (Contributed by Raymond Hettinger.)Several new POSIX functions (
getpgid()
,killpg()
,lchown()
,loadavg()
,major()
,makedev()
,minor()
, andmknod()
) were added to theposix
module that underlies theos
module. (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S.Otkidach.)In the
os
module, the*stat()
family of functions can now reportfractions of a second in a timestamp. Such time stamps are represented asfloats, similar to the value returned bytime.time()
.During testing, it was found that some applications will break if time stampsare floats. For compatibility, when using the tuple interface of the
stat_result
time stamps will be represented as integers. When usingnamed fields (a feature first introduced in Python 2.2), time stamps are stillrepresented as integers, unlessos.stat_float_times()
is invoked to enablefloat return values:>>>os.stat("/tmp").st_mtime1034791200>>>os.stat_float_times(True)>>>os.stat("/tmp").st_mtime1034791200.6335014
In Python 2.4, the default will change to always returning floats.
Application developers should enable this feature only if all their librarieswork properly when confronted with floating-point time stamps, or if they usethe tuple API. If used, the feature should be activated on an application levelinstead of trying to enable it on a per-use basis.
The
optparse
module contains a new parser for command-line argumentsthat can convert option values to a particular Python type and willautomatically generate a usage message. See the following section for moredetails.The old and never-documented
linuxaudiodev
module has been deprecated,and a new version namedossaudiodev
has been added. The module wasrenamed because the OSS sound drivers can be used on platforms other than Linux,and the interface has also been tidied and brought up to date in various ways.(Contributed by Greg Ward and Nicholas FitzRoy-Dale.)The new
platform
module contains a number of functions that try todetermine various properties of the platform you're running on. There arefunctions for getting the architecture, CPU type, the Windows OS version, andeven the Linux distribution version. (Contributed by Marc-André Lemburg.)The parser objects provided by the
pyexpat
module can now optionallybuffer character data, resulting in fewer calls to your character data handlerand therefore faster performance. Setting the parser object'sbuffer_text
attribute toTrue
will enable buffering.The
sample(population,k)
function was added to therandom
module.population is a sequence orxrange
object containing theelements of a population, andsample()
choosesk elements from thepopulation without replacing chosen elements.k can be any value up tolen(population)
. For example:>>>days=['Mo','Tu','We','Th','Fr','St','Sn']>>>random.sample(days,3)# Choose 3 elements['St', 'Sn', 'Th']>>>random.sample(days,7)# Choose 7 elements['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']>>>random.sample(days,7)# Choose 7 again['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']>>>random.sample(days,8)# Can't choose eightTraceback (most recent call last): File"<stdin>", line1, in? File"random.py", line414, insampleraiseValueError,"sample larger than population"ValueError:sample larger than population>>>random.sample(xrange(1,10000,2),10)# Choose ten odd nos. under 10000[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]
The
random
module now uses a new algorithm, the Mersenne Twister,implemented in C. It's faster and more extensively studied than the previousalgorithm.(All changes contributed by Raymond Hettinger.)
The
readline
module also gained a number of new functions:get_history_item()
,get_current_history_length()
, andredisplay()
.The
rexec
andBastion
modules have been declared dead, andattempts to import them will fail with aRuntimeError
. New-style classesprovide new ways to break out of the restricted execution environment providedbyrexec
, and no one has interest in fixing them or time to do so. Ifyou have applications usingrexec
, rewrite them to use something else.(Sticking with Python 2.2 or 2.1 will not make your applications any saferbecause there are known bugs in the
rexec
module in those versions. Torepeat: if you're usingrexec
, stop using it immediately.)The
rotor
module has been deprecated because the algorithm it uses forencryption is not believed to be secure. If you need encryption, use one of theseveral AES Python modules that are available separately.The
shutil
module gained amove(src,dest)
function thatrecursively moves a file or directory to a new location.Support for more advanced POSIX signal handling was added to the
signal
but then removed again as it proved impossible to make it work reliably acrossplatforms.The
socket
module now supports timeouts. You can call thesettimeout(t)
method on a socket object to set a timeout oft seconds.Subsequent socket operations that take longer thant seconds to complete willabort and raise asocket.timeout
exception.The original timeout implementation was by Tim O'Malley. Michael Gilfixintegrated it into the Python
socket
module and shepherded it through alengthy review. After the code was checked in, Guido van Rossum rewrote partsof it. (This is a good example of a collaborative development process inaction.)On Windows, the
socket
module now ships with Secure Sockets Layer(SSL) support.The value of the C
PYTHON_API_VERSION
macro is now exposed at thePython level assys.api_version
. The current exception can be cleared bycalling the newsys.exc_clear()
function.The new
tarfile
module allows reading from and writing totar-format archive files. (Contributed by Lars Gustäbel.)The new
textwrap
module contains functions for wrapping stringscontaining paragraphs of text. Thewrap(text,width)
function takes astring and returns a list containing the text split into lines of no more thanthe chosen width. Thefill(text,width)
function returns a singlestring, reformatted to fit into lines no longer than the chosen width. (As youcan guess,fill()
is built on top ofwrap()
. For example:>>>importtextwrap>>>paragraph="Not a whit, we defy augury: ... more text ...">>>textwrap.wrap(paragraph,60)["Not a whit, we defy augury: there's a special providence in", "the fall of a sparrow. If it be now, 'tis not to come; if it", ...]>>>printtextwrap.fill(paragraph,35)Not a whit, we defy augury: there'sa special providence in the fall ofa sparrow. If it be now, 'tis notto come; if it be not to come, itwill be now; if it be not now, yetit will come: the readiness is all.>>>
The module also contains a
TextWrapper
class that actually implementsthe text wrapping strategy. Both theTextWrapper
class and thewrap()
andfill()
functions support a number of additional keywordarguments for fine-tuning the formatting; consult the module's documentationfor details. (Contributed by Greg Ward.)The
thread
andthreading
modules now have companion modules,dummy_thread
anddummy_threading
, that provide a do-nothingimplementation of thethread
module's interface for platforms wherethreads are not supported. The intention is to simplify thread-aware modules(ones thatdon't rely on threads to run) by putting the following code at thetop:try:importthreadingas_threadingexceptImportError:importdummy_threadingas_threading
In this example,
_threading
is used as the module name to make it clearthat the module being used is not necessarily the actualthreading
module. Code can call functions and use classes in_threading
whether ornot threads are supported, avoiding anif
statement and making thecode slightly clearer. This module will not magically make multithreaded coderun without threads; code that waits for another thread to return or to dosomething will simply hang forever.The
time
module'sstrptime()
function has long been an annoyancebecause it uses the platform C library'sstrptime()
implementation, anddifferent platforms sometimes have odd bugs. Brett Cannon contributed aportable implementation that's written in pure Python and should behaveidentically on all platforms.The new
timeit
module helps measure how long snippets of Python codetake to execute. Thetimeit.py
file can be run directly from thecommand line, or the module'sTimer
class can be imported and useddirectly. Here's a short example that figures out whether it's faster toconvert an 8-bit string to Unicode by appending an empty Unicode string to it orby using theunicode()
function:importtimeittimer1=timeit.Timer('unicode("abc")')timer2=timeit.Timer('"abc" + u""')# Run three trialsprinttimer1.repeat(repeat=3,number=100000)printtimer2.repeat(repeat=3,number=100000)# On my laptop this outputs:# [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]# [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]
The
Tix
module has received various bug fixes and updates for thecurrent version of the Tix package.The
Tkinter
module now works with a thread-enabled version of Tcl.Tcl's threading model requires that widgets only be accessed from the thread inwhich they're created; accesses from another thread can cause Tcl to panic. Forcertain Tcl interfaces,Tkinter
will now automatically avoid this when awidget is accessed from a different thread by marshalling a command, passing itto the correct thread, and waiting for the results. Other interfaces can't behandled automatically butTkinter
will now raise an exception on such anaccess so that you can at least find out about the problem. Seehttps://mail.python.org/pipermail/python-dev/2002-December/031107.html for a moredetailed explanation of this change. (Implemented by Martin von Löwis.)Calling Tcl methods through
_tkinter
no longer returns only strings.Instead, if Tcl returns other objects those objects are converted to theirPython equivalent, if one exists, or wrapped with a_tkinter.Tcl_Obj
object if no Python equivalent exists. This behavior can be controlled throughthewantobjects()
method oftkapp
objects.When using
_tkinter
through theTkinter
module (as most Tkinterapplications will), this feature is always activated. It should not causecompatibility problems, since Tkinter would always convert string results toPython types where possible.If any incompatibilities are found, the old behavior can be restored by settingthe
wantobjects
variable in theTkinter
module to false beforecreating the firsttkapp
object.importTkinterTkinter.wantobjects=0
Any breakage caused by this change should be reported as a bug.
The
UserDict
module has a newDictMixin
class which definesall dictionary methods for classes that already have a minimum mappinginterface. This greatly simplifies writing classes that need to besubstitutable for dictionaries, such as the classes in theshelve
module.Adding the mix-in as a superclass provides the full dictionary interfacewhenever the class defines
__getitem__()
,__setitem__()
,__delitem__()
, andkeys()
. For example:>>>importUserDict>>>classSeqDict(UserDict.DictMixin):..."""Dictionary lookalike implemented with lists."""...def__init__(self):...self.keylist=[]...self.valuelist=[]...def__getitem__(self,key):...try:...i=self.keylist.index(key)...exceptValueError:...raiseKeyError...returnself.valuelist[i]...def__setitem__(self,key,value):...try:...i=self.keylist.index(key)...self.valuelist[i]=value...exceptValueError:...self.keylist.append(key)...self.valuelist.append(value)...def__delitem__(self,key):...try:...i=self.keylist.index(key)...exceptValueError:...raiseKeyError...self.keylist.pop(i)...self.valuelist.pop(i)...defkeys(self):...returnlist(self.keylist)...>>>s=SeqDict()>>>dir(s)# See that other dictionary methods are implemented['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__', '__init__', '__iter__', '__len__', '__module__', '__repr__', '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'valuelist', 'values']
(由 Raymond Hettinger 所貢獻。)
The DOM implementation in
xml.dom.minidom
can now generate XML outputin a particular encoding by providing an optional encoding argument to thetoxml()
andtoprettyxml()
methods of DOM nodes.The
xmlrpclib
module now supports an XML-RPC extension for handling nildata values such as Python'sNone
. Nil values are always supported onunmarshalling an XML-RPC response. To generate requests containingNone
,you must supply a true value for theallow_none parameter when creating aMarshaller
instance.The new
DocXMLRPCServer
module allows writing self-documenting XML-RPCservers. Run it in demo mode (as a program) to see it in action. Pointing theweb browser to the RPC server produces pydoc-style documentation; pointingxmlrpclib to the server allows invoking the actual methods. (Contributed byBrian Quinlan.)Support for internationalized domain names (RFCs 3454, 3490, 3491, and 3492)has been added. The "idna" encoding can be used to convert between a Unicodedomain name and the ASCII-compatible encoding (ACE) of that name.
>{}>{}>u"www.Alliancefrançaise.nu".encode("idna")'www.xn--alliancefranaise-npb.nu'
The
socket
module has also been extended to transparently convertUnicode hostnames to the ACE version before passing them to the C library.Modules that deal with hostnames such ashttplib
andftplib
)also support Unicode host names;httplib
also sends HTTPHost
headers using the ACE version of the domain name.urllib
supportsUnicode URLs with non-ASCII host names as long as thepath
part of the URLis ASCII only.To implement this change, the
stringprep
module, themkstringprep
tool and thepunycode
encoding have been added.
Date/Time Type¶
Date and time types suitable for expressing timestamps were added as thedatetime
module. The types don't support different calendars or manyfancy features, and just stick to the basics of representing time.
The three primary types are:date
, representing a day, month, and year;time
, consisting of hour, minute, and second; anddatetime
,which contains all the attributes of bothdate
andtime
.There's also atimedelta
class representing differences between twopoints in time, and time zone logic is implemented by classes inheriting fromthe abstracttzinfo
class.
You can create instances ofdate
andtime
by either supplyingkeyword arguments to the appropriate constructor, e.g.datetime.date(year=1972,month=10,day=15)
, or by using one of a number ofclass methods. For example, thetoday()
class method returns thecurrent local date.
Once created, instances of the date/time classes are all immutable. There are anumber of methods for producing formatted strings from objects:
>>>importdatetime>>>now=datetime.datetime.now()>>>now.isoformat()'2002-12-30T21:27:03.994956'>>>now.ctime()# Only available on date, datetime'Mon Dec 30 21:27:03 2002'>>>now.strftime('%Y%d %b')'2002 30 Dec'
Thereplace()
method allows modifying one or more fields of adate
ordatetime
instance, returning a new instance:
>>>d=datetime.datetime.now()>>>ddatetime.datetime(2002, 12, 30, 22, 15, 38, 827738)>>>d.replace(year=2001,hour=12)datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)>>>
Instances can be compared, hashed, and converted to strings (the result is thesame as that ofisoformat()
).date
anddatetime
instances can be subtracted from each other, and added totimedelta
instances. The largest missing feature is that there's no standard librarysupport for parsing strings and getting back adate
ordatetime
.
For more information, refer to the module's reference documentation.(Contributed by Tim Peters.)
The optparse Module¶
Thegetopt
module provides simple parsing of command-line arguments. Thenewoptparse
module (originally named Optik) provides more elaboratecommand-line parsing that follows the Unix conventions, automatically createsthe output for--help
, and can perform different actions for differentoptions.
You start by creating an instance ofOptionParser
and telling it whatyour program's options are.
importsysfromoptparseimportOptionParserop=OptionParser()op.add_option('-i','--input',action='store',type='string',dest='input',help='set input filename')op.add_option('-l','--length',action='store',type='int',dest='length',help='set maximum length of output')
Parsing a command line is then done by calling theparse_args()
method.
options,args=op.parse_args(sys.argv[1:])printoptionsprintargs
This returns an object containing all of the option values, and a list ofstrings containing the remaining arguments.
Invoking the script with the various arguments now works as you'd expect it to.Note that the length argument is automatically converted to an integer.
$./pythonopt.py-idataarg1<Values at 0x400cad4c: {'input': 'data', 'length': None}>['arg1']$./pythonopt.py--input=data--length=4<Values at 0x400cad2c: {'input': 'data', 'length': 4}>[]$
The help message is automatically generated for you:
$./pythonopt.py--helpusage: opt.py [options]options: -h, --help show this help message and exit -iINPUT, --input=INPUT set input filename -lLENGTH, --length=LENGTH set maximum length of output$
更多細節請見 module 文件。
Optik was written by Greg Ward, with suggestions from the readers of the GetoptSIG.
Pymalloc: A Specialized Object Allocator¶
Pymalloc, a specialized object allocator written by Vladimir Marangozov, was afeature added to Python 2.1. Pymalloc is intended to be faster than the systemmalloc()
and to have less memory overhead for allocation patterns typicalof Python programs. The allocator uses C'smalloc()
function to get largepools of memory and then fulfills smaller memory requests from these pools.
In 2.1 and 2.2, pymalloc was an experimental feature and wasn't enabled bydefault; you had to explicitly enable it when compiling Python by providing the--with-pymalloc
option to theconfigure script. In 2.3,pymalloc has had further enhancements and is now enabled by default; you'll haveto supply--without-pymalloc
to disable it.
This change is transparent to code written in Python; however, pymalloc mayexpose bugs in C extensions. Authors of C extension modules should test theircode with pymalloc enabled, because some incorrect code may cause core dumps atruntime.
There's one particularly common error that causes problems. There are a numberof memory allocation functions in Python's C API that have previously just beenaliases for the C library'smalloc()
andfree()
, meaning that ifyou accidentally called mismatched functions the error wouldn't be noticeable.When the object allocator is enabled, these functions aren't aliases ofmalloc()
andfree()
any more, and calling the wrong function tofree memory may get you a core dump. For example, if memory was allocated usingPyObject_Malloc()
, it has to be freed usingPyObject_Free()
, notfree()
. A few modules included with Python fell afoul of this and had tobe fixed; doubtless there are more third-party modules that will have the sameproblem.
As part of this change, the confusing multiple interfaces for allocating memoryhave been consolidated down into two API families. Memory allocated with onefamily must not be manipulated with functions from the other family. There isone family for allocating chunks of memory and another family of functionsspecifically for allocating Python objects.
To allocate and free an undistinguished chunk of memory use the "raw memory"family:
PyMem_Malloc()
,PyMem_Realloc()
, andPyMem_Free()
.The "object memory" family is the interface to the pymalloc facility describedabove and is biased towards a large number of "small" allocations:
PyObject_Malloc()
,PyObject_Realloc()
, andPyObject_Free()
.To allocate and free Python objects, use the "object" family
PyObject_New
,PyObject_NewVar
, andPyObject_Del()
.
Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debuggingfeatures to catch memory overwrites and doubled frees in both extension modulesand in the interpreter itself. To enable this support, compile a debuggingversion of the Python interpreter by runningconfigure with--with-pydebug
.
To aid extension writers, a header fileMisc/pymemcompat.h
isdistributed with the source to Python 2.3 that allows Python extensions to usethe 2.3 interfaces to memory allocation while compiling against any version ofPython since 1.5.2. You would copy the file from Python's source distributionand bundle it with the source of your extension.
也參考
- https://hg.python.org/cpython/file/default/Objects/obmalloc.c
For the full details of the pymalloc implementation, see the comments atthe top of the file
Objects/obmalloc.c
in the Python source code.The above link points to the file within the python.org SVN browser.
建置和 C API 變更¶
Python 建置程序和 C API 的變更包括:
The cycle detection implementation used by the garbage collection has provento be stable, so it's now been made mandatory. You can no longer compile Pythonwithout it, and the
--with-cycle-gc
switch toconfigure hasbeen removed.Python can now optionally be built as a shared library(
libpython2.3.so
) by supplying--enable-shared
when runningPython'sconfigure script. (Contributed by Ondrej Palkovsky.)The
DL_EXPORT
andDL_IMPORT
macros are now deprecated.Initialization functions for Python extension modules should now be declaredusing the new macroPyMODINIT_FUNC
, while the Python core willgenerally use thePyAPI_FUNC
andPyAPI_DATA
macros.The interpreter can be compiled without any docstrings for the built-infunctions and modules by supplying
--without-doc-strings
to theconfigure script. This makes the Python executable about 10% smaller,but will also mean that you can't get help for Python's built-ins. (Contributedby Gustavo Niemeyer.)The
PyArg_NoArgs()
macro is now deprecated, and code that uses itshould be changed. For Python 2.2 and later, the method definition table canspecify theMETH_NOARGS
flag, signalling that there are no arguments,and the argument checking can then be removed. If compatibility with pre-2.2versions of Python is important, the code could usePyArg_ParseTuple(args,"")
instead, but this will be slower than usingMETH_NOARGS
.PyArg_ParseTuple()
accepts new format characters for various sizes ofunsigned integers:B
forunsignedchar,H
forunsignedshortint,I
forunsignedint, andK
forunsignedlonglong.A new function,
PyObject_DelItemString(mapping,char*key)
was addedas shorthand forPyObject_DelItem(mapping,PyString_New(key))
.File objects now manage their internal string buffer differently, increasingit exponentially when needed. This results in the benchmark tests in
Lib/test/test_bufio.py
speeding up considerably (from 57 seconds to 1.7seconds, according to one measurement).It's now possible to define class and static methods for a C extension type bysetting either the
METH_CLASS
orMETH_STATIC
flags in amethod'sPyMethodDef
structure.Python now includes a copy of the Expat XML parser's source code, removing anydependence on a system version or local installation of Expat.
If you dynamically allocate type objects in your extension, you should beaware of a change in the rules relating to the
__module__
and__name__
attributes. In summary, you will want to ensure the type'sdictionary contains a'__module__'
key; making the module name the part ofthe type name leading up to the final period will no longer have the desiredeffect. For more detail, read the API reference documentation or the source.
Port-Specific Changes¶
Support for a port to IBM's OS/2 using the EMX runtime environment was mergedinto the main Python source tree. EMX is a POSIX emulation layer over the OS/2system APIs. The Python port for EMX tries to support all the POSIX-likecapability exposed by the EMX runtime, and mostly succeeds;fork()
andfcntl()
are restricted by the limitations of the underlying emulationlayer. The standard OS/2 port, which uses IBM's Visual Age compiler, alsogained support for case-sensitive import semantics as part of the integration ofthe EMX port into CVS. (Contributed by Andrew MacIntyre.)
On MacOS, most toolbox modules have been weaklinked to improve backwardcompatibility. This means that modules will no longer fail to load if a singleroutine is missing on the current OS version. Instead calling the missingroutine will raise an exception. (Contributed by Jack Jansen.)
The RPM spec files, found in theMisc/RPM/
directory in the Pythonsource distribution, were updated for 2.3. (Contributed by Sean Reifschneider.)
Other new platforms now supported by Python include AtheOS(http://www.atheos.cx/), GNU/Hurd, and OpenVMS.
Other Changes and Fixes¶
As usual, there were a bunch of other improvements and bugfixes scatteredthroughout the source tree. A search through the CVS change logs finds therewere 523 patches applied and 514 bugs fixed between Python 2.2 and 2.3. Bothfigures are likely to be underestimates.
Some of the more notable changes are:
If the
PYTHONINSPECT
environment variable is set, the Pythoninterpreter will enter the interactive prompt after running a Python program, asif Python had been invoked with the-i
option. The environmentvariable can be set before running the Python interpreter, or it can be set bythe Python program as part of its execution.The
regrtest.py
script now provides a way to allow "all resourcesexceptfoo." A resource name passed to the-u
option can now beprefixed with a hyphen ('-'
) to mean "remove this resource." For example,the option '-uall,-bsddb
' could be used to enable the use of all resourcesexceptbsddb
.The tools used to build the documentation now work under Cygwin as well asUnix.
The
SET_LINENO
opcode has been removed. Back in the mists of time, thisopcode was needed to produce line numbers in tracebacks and support tracefunctions (for, e.g.,pdb
). Since Python 1.5, the line numbers intracebacks have been computed using a different mechanism that works with"python -O". For Python 2.3 Michael Hudson implemented a similar scheme todetermine when to call the trace function, removing the need forSET_LINENO
entirely.It would be difficult to detect any resulting difference from Python code, apartfrom a slight speed up when Python is run without
-O
.C extensions that access the
f_lineno
field of frame objects shouldinstead callPyCode_Addr2Line(f->f_code,f->f_lasti)
. This will have theadded effect of making the code work as desired under "python -O" in earlierversions of Python.A nifty new feature is that trace functions can now assign to the
f_lineno
attribute of frame objects, changing the line that will beexecuted next. Ajump
command has been added to thepdb
debuggertaking advantage of this new feature. (Implemented by Richie Hindle.)
Porting to Python 2.3¶
This section lists previously described changes that may require changes to yourcode:
yield
is now always a keyword; if it's used as a variable name inyour code, a different name must be chosen.For stringsX andY,
XinY
now works ifX is more than onecharacter long.The
int()
type constructor will now return a long integer instead ofraising anOverflowError
when a string or floating-point number is toolarge to fit into an integer.If you have Unicode strings that contain 8-bit characters, you must declarethe file's encoding (UTF-8, Latin-1, or whatever) by adding a comment to the topof the file. See sectionPEP 263: Source Code Encodings for more information.
Calling Tcl methods through
_tkinter
no longer returns only strings.Instead, if Tcl returns other objects those objects are converted to theirPython equivalent, if one exists, or wrapped with a_tkinter.Tcl_Obj
object if no Python equivalent exists.Large octal and hex literals such as
0xffffffff
now trigger aFutureWarning
. Currently they're stored as 32-bit numbers and result in anegative value, but in Python 2.4 they'll become positive long integers.There are a few ways to fix this warning. If you really need a positive number,just add an
L
to the end of the literal. If you're trying to get a 32-bitinteger with low bits set and have previously used an expression such as~(1<<31)
, it's probably clearest to start with all bits set and clear thedesired upper bits. For example, to clear just the top bit (bit 31), you couldwrite0xffffffffL&~(1L<<31)
.You can no longer disable assertions by assigning to
__debug__
.The Distutils
setup()
function has gained various new keyword argumentssuch asdepends. Old versions of the Distutils will abort if passed unknownkeywords. A solution is to check for the presence of the newget_distutil_options()
function in yoursetup.py
and only uses thenew keywords with a version of the Distutils that supports them:fromdistutilsimportcorekw={'sources':'foo.c',...}ifhasattr(core,'get_distutil_options'):kw['depends']=['foo.h']ext=Extension(**kw)
Using
None
as a variable name will now result in aSyntaxWarning
warning.Names of extension types defined by the modules included with Python nowcontain the module and a
'.'
in front of the type name.
致謝¶
The author would like to thank the following people for offering suggestions,corrections and assistance with various drafts of this article: Jeff Bauer,Simon Brunning, Brett Cannon, Michael Chermside, Andrew Dalke, Scott DavidDaniels, Fred L. Drake, Jr., David Fraser, Kelly Gerber, Raymond Hettinger,Michael Hudson, Chris Lambert, Detlef Lannert, Martin von Löwis, AndrewMacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer, Neal Norwitz, HansNowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, RomanSuzi, Jason Tishler, Just van Rossum.