Python 2.6 有什麼新功能¶
- 作者:
A.M. Kuchling (amk at amk.ca)
本文介紹了已於 2008 年 10 月 1 日發布的 Python 2.6 有哪些新功能。發布時間表請見PEP 361。
The major theme of Python 2.6 is preparing the migration path toPython 3.0, a major redesign of the language. Whenever possible,Python 2.6 incorporates new features and syntax from 3.0 whileremaining compatible with existing code by not removing older featuresor syntax. When it's not possible to do that, Python 2.6 tries to dowhat it can, adding compatibility functions in afuture_builtins
module and a-3
switch to warn aboutusages that will become unsupported in 3.0.
Some significant new packages have been added to the standard library,such as themultiprocessing
andjson
modules, butthere aren't many new features that aren't related to Python 3.0 insome way.
Python 2.6 also sees a number of improvements and bugfixes throughoutthe source. A search through the change logs finds there were 259patches applied and 612 bugs fixed between Python 2.5 and 2.6. Bothfigures are likely to be underestimates.
This article doesn't attempt to provide a complete specification ofthe new features, but instead provides a convenient overview. Forfull details, you should refer to the documentation for Python 2.6. Ifyou want to understand the rationale for the design andimplementation, refer to the PEP for a particular new feature.Whenever possible, "What's New in Python" links to the bug/patch itemfor each change.
Python 3.0¶
The development cycle for Python versions 2.6 and 3.0 wassynchronized, with the alpha and beta releases for both versions beingmade on the same days. The development of 3.0 has influenced manyfeatures in 2.6.
Python 3.0 is a far-ranging redesign of Python that breakscompatibility with the 2.x series. This means that existing Pythoncode will need some conversion in order to run onPython 3.0. However, not all the changes in 3.0 necessarily breakcompatibility. In cases where new features won't cause existing codeto break, they've been backported to 2.6 and are described in thisdocument in the appropriate place. Some of the 3.0-derived featuresare:
A
__complex__()
method for converting objects to a complex number.Alternate syntax for catching exceptions:
exceptTypeErrorasexc
.The addition of
functools.reduce()
as a synonym for the built-inreduce()
function.
Python 3.0 adds several new built-in functions and changes thesemantics of some existing builtins. Functions that are new in 3.0such asbin()
have simply been added to Python 2.6, but existingbuiltins haven't been changed; instead, thefuture_builtins
module has versions with the new 3.0 semantics. Code written to becompatible with 3.0 can dofromfuture_builtinsimporthex,map
asnecessary.
A new command-line switch,-3
, enables warningsabout features that will be removed in Python 3.0. You can run codewith this switch to see how much work will be necessary to portcode to 3.0. The value of this switch is availableto Python code as the boolean variablesys.py3kwarning
,and to C extension code asPy_Py3kWarningFlag
.
Changes to the Development Process¶
While 2.6 was being developed, the Python development processunderwent two significant changes: we switched from SourceForge'sissue tracker to a customized Roundup installation, and thedocumentation was converted from LaTeX to reStructuredText.
New Issue Tracker: Roundup¶
For a long time, the Python developers had been growing increasinglyannoyed by SourceForge's bug tracker. SourceForge's hosted solutiondoesn't permit much customization; for example, it wasn't possible tocustomize the life cycle of issues.
The infrastructure committee of the Python Software Foundationtherefore posted a call for issue trackers, asking volunteers to setup different products and import some of the bugs and patches fromSourceForge. Four different trackers were examined:Jira,Launchpad,Roundup, andTrac.The committee eventually settled on Jiraand Roundup as the two candidates. Jira is a commercial product thatoffers no-cost hosted instances to free-software projects; Roundupis an open-source project that requires volunteersto administer it and a server to host it.
After posting a call for volunteers, a new Roundup installation wasset up athttps://bugs.python.org. One installation of Roundup canhost multiple trackers, and this server now also hosts issue trackersfor Jython and for the Python web site. It will surely findother uses in the future. Where possible,this edition of "What's New in Python" links to the bug/patchitem for each change.
Hosting of the Python bug tracker is kindly provided byUpfront Systemsof Stellenbosch, South Africa. Martin von Löwis put alot of effort into importing existing bugs and patches fromSourceForge; his scripts for this import operation are athttps://svn.python.org/view/tracker/importer/
and may be useful toother projects wishing to move from SourceForge to Roundup.
也參考
- https://bugs.python.org
Python 問題追蹤系統。
- https://bugs.jython.org:
Jython 問題追蹤系統。
- https://roundup.sourceforge.io/
Roundup downloads and documentation.
- https://svn.python.org/view/tracker/importer/
Martin von Löwis 的轉換腳本。
新文件格式:使用 Sphinx 的 reStructuredText¶
The Python documentation was written using LaTeX since the projectstarted around 1989. In the 1980s and early 1990s, most documentationwas printed out for later study, not viewed online. LaTeX was widelyused because it provided attractive printed output while remainingstraightforward to write once the basic rules of the markup werelearned.
Today LaTeX is still used for writing publications destined forprinting, but the landscape for programming tools has shifted. We nolonger print out reams of documentation; instead, we browse through itonline and HTML has become the most important format to support.Unfortunately, converting LaTeX to HTML is fairly complicated and FredL. Drake Jr., the long-time Python documentation editor, spent a lotof time maintaining the conversion process. Occasionally people wouldsuggest converting the documentation into SGML and later XML, butperforming a good conversion is a major task and no one ever committedthe time required to finish the job.
During the 2.6 development cycle, Georg Brandl put a lot of effortinto building a new toolchain for processing the documentation. Theresulting package is called Sphinx, and is available fromhttps://www.sphinx-doc.org/.
Sphinx concentrates on HTML output, producing attractively styled andmodern HTML; printed output is still supported through conversion toLaTeX. The input format is reStructuredText, a markup syntaxsupporting custom extensions and directives that is commonly used inthe Python community.
Sphinx is a standalone package that can be used for writing, andalmost two dozen other projects(listed on the Sphinx web site)have adopted Sphinx as their documentation tool.
也參考
- Python 文件撰寫
說明如何為 Python 撰寫文件。
- Sphinx
Sphinx 工具鏈的文件和程式碼。
- Docutils
底層 reStructuredText 剖析器和工具集。
PEP 343:'with' 陳述式¶
The previous version, Python 2.5, added the 'with
'statement as an optional feature, to be enabled by afrom__future__importwith_statement
directive. In 2.6 the statement no longer needs tobe specially enabled; this means thatwith
is now always akeyword. The rest of this section is a copy of the correspondingsection from the "What's New in Python 2.5" document; if you'refamiliar with the 'with
' statementfrom Python 2.5, you can skip this section.
The 'with
' statement clarifies code that previously would usetry...finally
blocks to ensure that clean-up code is executed. In thissection, I'll discuss the statement as it will commonly be used. In the nextsection, I'll examine the implementation details and show how to write objectsfor use with this statement.
The 'with
' statement is a control-flow structure whose basicstructure is:
withexpression[asvariable]:with-block
The expression is evaluated, and it should result in an object that supports thecontext management protocol (that is, has__enter__()
and__exit__()
methods).
The object's__enter__()
is called beforewith-block is executed andtherefore can run set-up code. It also may return a value that is bound to thenamevariable, if given. (Note carefully thatvariable isnot assignedthe result ofexpression.)
After execution of thewith-block is finished, the object's__exit__()
method is called, even if the block raised an exception, and can therefore runclean-up code.
Some standard Python objects now support the context management protocol and canbe used with the 'with
' statement. File objects are one example:
withopen('/etc/passwd','r')asf:forlineinf:printline...更多處理程式碼...
After this statement has executed, the file object inf will have beenautomatically closed, even if thefor
loop raised an exceptionpart-way through the block.
備註
In this case,f is the same object created byopen()
, because__enter__()
returnsself.
Thethreading
module's locks and condition variables also support the'with
' statement:
lock=threading.Lock()withlock:# Critical section of code...
The lock is acquired before the block is executed and always released once theblock is complete.
Thelocalcontext()
function in thedecimal
module makes it easyto save and restore the current decimal context, which encapsulates the desiredprecision and rounding characteristics for computations:
fromdecimalimportDecimal,Context,localcontext# Displays with default precision of 28 digitsv=Decimal('578')printv.sqrt()withlocalcontext(Context(prec=16)):# All code in this block uses a precision of 16 digits.# The original context is restored on exiting the block.printv.sqrt()
Writing Context Managers¶
Under the hood, the 'with
' statement is fairly complicated. Mostpeople will only use 'with
' in company with existing objects anddon't need to know these details, so you can skip the rest of this section ifyou like. Authors of new objects will need to understand the details of theunderlying implementation and should keep reading.
A high-level explanation of the context management protocol is:
The expression is evaluated and should result in an object called a "contextmanager". The context manager must have
__enter__()
and__exit__()
methods.The context manager's
__enter__()
method is called. The value returnedis assigned toVAR. If noasVAR
clause is present, the value is simplydiscarded.BLOCK 中的程式碼會被執行。
IfBLOCK raises an exception, the context manager's
__exit__()
methodis called with three arguments, the exception details (type,value,traceback
,the same values returned bysys.exc_info()
, which can also beNone
if no exception occurred). The method's return value controls whether an exceptionis re-raised: any false value re-raises the exception, andTrue
will resultin suppressing it. You'll only rarely want to suppress the exception, becauseif you do the author of the code containing the 'with
' statement willnever realize anything went wrong.IfBLOCK didn't raise an exception, the
__exit__()
method is stillcalled, buttype,value, andtraceback are allNone
.
Let's think through an example. I won't present detailed code but will onlysketch the methods necessary for a database that supports transactions.
(For people unfamiliar with database terminology: a set of changes to thedatabase are grouped into a transaction. Transactions can be either committed,meaning that all the changes are written into the database, or rolled back,meaning that the changes are all discarded and the database is unchanged. Seeany database textbook for more information.)
Let's assume there's an object representing a database connection. Our goal willbe to let the user write code like this:
db_connection=DatabaseConnection()withdb_connectionascursor:cursor.execute('insert into ...')cursor.execute('delete from ...')# ... 更多操作 ...
The transaction should be committed if the code in the block runs flawlessly orrolled back if there's an exception. Here's the basic interface forDatabaseConnection
that I'll assume:
classDatabaseConnection:# Database interfacedefcursor(self):"Returns a cursor object and starts a new transaction"defcommit(self):"Commits current transaction"defrollback(self):"Rolls back current transaction"
The__enter__()
method is pretty easy, having only to start a newtransaction. For this application the resulting cursor object would be a usefulresult, so the method will return it. The user can then addascursor
totheir 'with
' statement to bind the cursor to a variable name.
classDatabaseConnection:...def__enter__(self):# Code to start a new transactioncursor=self.cursor()returncursor
The__exit__()
method is the most complicated because it's where most ofthe work has to be done. The method has to check if an exception occurred. Ifthere was no exception, the transaction is committed. The transaction is rolledback if there was an exception.
In the code below, execution will just fall off the end of the function,returning the default value ofNone
.None
is false, so the exceptionwill be re-raised automatically. If you wished, you could be more explicit andadd areturn
statement at the marked location.
classDatabaseConnection:...def__exit__(self,type,value,tb):iftbisNone:# No exception, so commitself.commit()else:# Exception occurred, so rollback.self.rollback()# return False
contextlib 模組¶
Thecontextlib
module provides some functions and a decorator thatare useful when writing objects for use with the 'with
' statement.
The decorator is calledcontextmanager()
, and lets you write a singlegenerator function instead of defining a new class. The generator should yieldexactly one value. The code up to theyield
will be executed as the__enter__()
method, and the value yielded will be the method's returnvalue that will get bound to the variable in the 'with
' statement'sas
clause, if any. The code after theyield
will beexecuted in the__exit__()
method. Any exception raised in the block willbe raised by theyield
statement.
Using this decorator, our database example from the previous sectioncould be written as:
fromcontextlibimportcontextmanager@contextmanagerdefdb_transaction(connection):cursor=connection.cursor()try:yieldcursorexcept:connection.rollback()raiseelse:connection.commit()db=DatabaseConnection()withdb_transaction(db)ascursor:...
Thecontextlib
module also has anested(mgr1,mgr2,...)
functionthat combines a number of context managers so you don't need to write nested'with
' statements. In this example, the single 'with
'statement both starts a database transaction and acquires a thread lock:
lock=threading.Lock()withnested(db_transaction(db),lock)as(cursor,locked):...
Finally, theclosing()
function returns its argument so that it can bebound to a variable, and calls the argument's.close()
method at the endof the block.
importurllib,sysfromcontextlibimportclosingwithclosing(urllib.urlopen('http://www.yahoo.com'))asf:forlineinf:sys.stdout.write(line)
也參考
- PEP 343 - "with" 陳述式
PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a'
with
' statement, which can be helpful in learning how the statementworks.
contextlib
模組的文件。
PEP 366: Explicit Relative Imports From a Main Module¶
Python's-m
switch allows running a module as a script.When you ran a module that was located inside a package, relativeimports didn't work correctly.
The fix for Python 2.6 adds amodule.__package__
attribute.When this attribute is present, relative imports will berelative to the value of this attribute instead of the__name__
attribute.
PEP 302-style importers can then set__package__
as necessary.Therunpy
module that implements the-m
switch nowdoes this, so relative imports will now work correctly in scriptsrunning from inside a package.
PEP 370: Per-usersite-packages
Directory¶
When you run Python, the module search pathsys.path
usuallyincludes a directory whose path ends in"site-packages"
. Thisdirectory is intended to hold locally installed packages available toall users using a machine or a particular site installation.
Python 2.6 introduces a convention for user-specific site directories.The directory varies depending on the platform:
Unix 和 Mac OS X:
~/.local/
Windows:
%APPDATA%/Python
Within this directory, there will be version-specific subdirectories,such aslib/python2.6/site-packages
on Unix/Mac OS andPython26/site-packages
on Windows.
If you don't like the default directory, it can be overridden by anenvironment variable.PYTHONUSERBASE
sets the rootdirectory used for all Python versions supporting this feature. OnWindows, the directory for application-specific data can be changed bysetting theAPPDATA
environment variable. You can alsomodify thesite.py
file for your Python installation.
The feature can be disabled entirely by running Python with the-s
option or setting thePYTHONNOUSERSITE
environment variable.
也參考
- PEP 370 - Per-user
site-packages
Directory 由 Christian Heimes 撰寫 PEP 與實作。
PEP 371: Themultiprocessing
Package¶
The newmultiprocessing
package lets Python programs create newprocesses that will perform a computation and return a result to theparent. The parent and child processes can communicate using queuesand pipes, synchronize their operations using locks and semaphores,and can share simple arrays of data.
Themultiprocessing
module started out as an exact emulation ofthethreading
module using processes instead of threads. Thatgoal was discarded along the path to Python 2.6, but the generalapproach of the module is still similar. The fundamental classis theProcess
, which is passed a callable object anda collection of arguments. Thestart()
methodsets the callable running in a subprocess, after which you can calltheis_alive()
method to check whether the subprocess is still runningand thejoin()
method to wait for the process to exit.
Here's a simple example where the subprocess will calculate afactorial. The function doing the calculation is written strangely sothat it takes significantly longer when the input argument is amultiple of 4.
importtimefrommultiprocessingimportProcess,Queuedeffactorial(queue,N):"計算階乘。"# 如果 N 是 4 的倍數,則此函式將花費更多時間。if(N%4)==0:time.sleep(.05*N/4)# 計算結果fact=1Lforiinrange(1,N+1):fact=fact*i# 將結果放進佇列裡queue.put(fact)if__name__=='__main__':queue=Queue()N=5p=Process(target=factorial,args=(queue,N))p.start()p.join()result=queue.get()print'Factorial',N,'=',result
AQueue
is used to communicate the result of the factorial.TheQueue
object is stored in a global variable.The child process will use the value of the variable when the childwas created; because it's aQueue
, parent and child can usethe object to communicate. (If the parent were to change the value ofthe global variable, the child's value would be unaffected, and viceversa.)
Two other classes,Pool
andManager
, providehigher-level interfaces.Pool
will create a fixed number ofworker processes, and requests can then be distributed to the workersby callingapply()
orapply_async()
to add a single request,andmap()
ormap_async()
to add a number ofrequests. The following code uses aPool
to spread requestsacross 5 worker processes and retrieve a list of results:
frommultiprocessingimportPooldeffactorial(N,dictionary):"計算階乘。"...p=Pool(5)result=p.map(factorial,range(1,1000,10))forvinresult:printv
This produces the following output:
13991680051090942171709440000822283865417792281772556288000000033452526613163807108170062053440751665152000000000...
The other high-level interface, theManager
class, creates aseparate server process that can hold master copies of Python datastructures. Other processes can then access and modify these datastructures using proxy objects. The following example creates ashared dictionary by calling thedict()
method; the workerprocesses then insert values into the dictionary. (Locking is notdone for you automatically, which doesn't matter in this example.Manager
's methods also includeLock()
,RLock()
,andSemaphore()
to create shared locks.)
importtimefrommultiprocessingimportPool,Managerdeffactorial(N,dictionary):"Compute a factorial."# Calculate the resultfact=1Lforiinrange(1,N+1):fact=fact*i# Store result in dictionarydictionary[N]=factif__name__=='__main__':p=Pool(5)mgr=Manager()d=mgr.dict()# Create shared dictionary# Run tasks using the poolforNinrange(1,1000,10):p.apply_async(factorial,(N,d))# Mark pool as closed -- no more tasks can be added.p.close()# Wait for tasks to exitp.join()# Output resultsfork,vinsorted(d.items()):printk,v
This will produce the output:
111139916800215109094217170944000031822283865417792281772556288000000041334525266131638071081700620534407516651520000000005115511187532873822802242430164693032110632597200169861120000...
也參考
multiprocessing
模組的文件。
- PEP 371 - Addition of the multiprocessing package
PEP written by Jesse Noller and Richard Oudkerk;implemented by Richard Oudkerk and Jesse Noller.
PEP 3101: Advanced String Formatting¶
In Python 3.0, the%
operator is supplemented by a more powerful stringformatting method,format()
. Support for thestr.format()
methodhas been backported to Python 2.6.
In 2.6, both 8-bit and Unicode strings have a.format()
method thattreats the string as a template and takes the arguments to be formatted.The formatting template uses curly brackets ({
,}
) as special characters:
>>># Substitute positional argument 0 into the string.>>>"User ID:{0}".format("root")'User ID: root'>>># Use the named keyword arguments>>>"User ID:{uid} Last seen:{last_login}".format(...uid="root",...last_login="5 Mar 2008 07:20")'User ID: root Last seen: 5 Mar 2008 07:20'
Curly brackets can be escaped by doubling them:
>>>"Empty dict: {{}}".format()"Empty dict: {}"
Field names can be integers indicating positional arguments, such as{0}
,{1}
, etc. or names of keyword arguments. You can alsosupply compound field names that read attributes or access dictionary keys:
>>>importsys>>>print'Platform:{0.platform}\nPython version:{0.version}'.format(sys)Platform: darwinPython version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41)[GCC 4.0.1 (Apple Computer, Inc. build 5367)]'>>>importmimetypes>>>'Content-type:{0[.mp4]}'.format(mimetypes.types_map)'Content-type: video/mp4'
Note that when using dictionary-style notation such as[.mp4]
, youdon't need to put any quotation marks around the string; it will lookup the value using.mp4
as the key. Strings beginning with anumber will be converted to an integer. You can't write morecomplicated expressions inside a format string.
So far we've shown how to specify which field to substitute into theresulting string. The precise formatting used is also controllable byadding a colon followed by a format specifier. For example:
>>># Field 0: left justify, pad to 15 characters>>># Field 1: right justify, pad to 6 characters>>>fmt='{0:15} ${1:>6}'>>>fmt.format('Registration',35)'Registration $ 35'>>>fmt.format('Tutorial',50)'Tutorial $ 50'>>>fmt.format('Banquet',125)'Banquet $ 125'
Format specifiers can reference other fields through nesting:
>>>fmt='{0:{1}}'>>>width=15>>>fmt.format('Invoice #1234',width)'Invoice #1234 '>>>width=35>>>fmt.format('Invoice #1234',width)'Invoice #1234 '
The alignment of a field within the desired width can be specified:
字元 | 效果 |
---|---|
< (default) | Left-align |
> | Right-align |
^ | Center |
= | (For numeric types only) Pad after the sign. |
Format specifiers can also include a presentation type, whichcontrols how the value is formatted. For example, floating-point numberscan be formatted as a general number or in exponential notation:
>>>'{0:g}'.format(3.75)'3.75'>>>'{0:e}'.format(3.75)'3.750000e+00'
A variety of presentation types are available. Consult the 2.6documentation for acomplete list; here's a sample:
| Binary. Outputs the number in base 2. |
| Character. Converts the integer to the corresponding Unicode characterbefore printing. |
| Decimal Integer. Outputs the number in base 10. |
| Octal format. Outputs the number in base 8. |
| Hex format. Outputs the number in base 16, using lower-case letters forthe digits above 9. |
| Exponent notation. Prints the number in scientific notation using theletter 'e' to indicate the exponent. |
| General format. This prints the number as a fixed-point number, unlessthe number is too large, in which case it switches to 'e' exponentnotation. |
| Number. This is the same as 'g' (for floats) or 'd' (for integers),except that it uses the current locale setting to insert the appropriatenumber separator characters. |
| Percentage. Multiplies the number by 100 and displays in fixed ('f')format, followed by a percent sign. |
Classes and types can define a__format__()
method to control how they'reformatted. It receives a single argument, the format specifier:
def__format__(self,format_spec):ifisinstance(format_spec,unicode):returnunicode(str(self))else:returnstr(self)
There's also aformat()
builtin that will format a singlevalue. It calls the type's__format__()
method with theprovided specifier:
>>>format(75.6564,'.2f')'75.66'
PEP 3105:print
As a Function¶
Theprint
statement becomes theprint()
function in Python 3.0.Makingprint()
a function makes it possible to replace the functionby doingdefprint(...)
or importing a new function from somewhere else.
Python 2.6 has a__future__
import that removesprint
as languagesyntax, letting you use the functional form instead. For example:
>>>from__future__importprint_function>>>print('# of entries',len(dictionary),file=sys.stderr)
The signature of the new function is:
defprint(*args,sep=' ',end='\n',file=None)
The parameters are:
args: positional arguments whose values will be printed out.
sep: the separator, which will be printed between arguments.
end: the ending text, which will be printed after all of thearguments have been output.
file: the file object to which the output will be sent.
也參考
- PEP 3105 - 將 print 變成函式
由 Georg Brandl 撰寫 PEP。
PEP 3110: Exception-Handling Changes¶
One error that Python programmers occasionally makeis writing the following code:
try:...exceptTypeError,ValueError:# 錯誤!...
The author is probably trying to catch bothTypeError
andValueError
exceptions, but this code actually does somethingdifferent: it will catchTypeError
and bind the resultingexception object to the local name"ValueError"
. TheValueError
exception will not be caught at all. The correctcode specifies a tuple of exceptions:
try:...except(TypeError,ValueError):...
This error happens because the use of the comma here is ambiguous:does it indicate two different nodes in the parse tree, or a singlenode that's a tuple?
Python 3.0 makes this unambiguous by replacing the comma with the word"as". To catch an exception and store the exception object in thevariableexc
, you must write:
try:...exceptTypeErrorasexc:...
Python 3.0 will only support the use of "as", and therefore interpretsthe first example as catching two different exceptions. Python 2.6supports both the comma and "as", so existing code will continue towork. We therefore suggest using "as" when writing new Python codethat will only be executed with 2.6.
也參考
- PEP 3110 - Catching Exceptions in Python 3000
由 Collin Winter 撰寫 PEP 與實作。
PEP 3112: Byte Literals¶
Python 3.0 adopts Unicode as the language's fundamental string type anddenotes 8-bit literals differently, either asb'string'
or using abytes
constructor. For future compatibility,Python 2.6 addsbytes
as a synonym for thestr
type,and it also supports theb''
notation.
The 2.6str
differs from 3.0'sbytes
type in variousways; most notably, the constructor is completely different. In 3.0,bytes([65,66,67])
is 3 elements long, containing the bytesrepresentingABC
; in 2.6,bytes([65,66,67])
returns the12-byte string representing thestr()
of the list.
The primary use ofbytes
in 2.6 will be to write tests ofobject type such asisinstance(x,bytes)
. This will help the 2to3converter, which can't tell whether 2.x code intends strings tocontain either characters or 8-bit bytes; you can nowuse eitherbytes
orstr
to represent your intentionexactly, and the resulting code will also be correct in Python 3.0.
There's also a__future__
import that causes all string literalsto become Unicode strings. This means that\u
escape sequencescan be used to include Unicode characters:
from__future__importunicode_literalss=('\u751f\u3080\u304e\u3000\u751f\u3054''\u3081\u3000\u751f\u305f\u307e\u3054')printlen(s)# 12 個 Unicode 字元
At the C level, Python 3.0 will rename the existing 8-bitstring type, calledPyStringObject
in Python 2.x,toPyBytesObject
. Python 2.6 uses#define
to support using the namesPyBytesObject()
,PyBytes_Check()
,PyBytes_FromStringAndSize()
,and all the other functions and macros used with strings.
Instances of thebytes
type are immutable justas strings are. A newbytearray
type stores a mutablesequence of bytes:
>>>bytearray([65,66,67])bytearray(b'ABC')>>>b=bytearray(u'\u21ef\u3244','utf-8')>>>bbytearray(b'\xe2\x87\xaf\xe3\x89\x84')>>>b[0]='\xe3'>>>bbytearray(b'\xe3\x87\xaf\xe3\x89\x84')>>>unicode(str(b),'utf-8')u'\u31ef \u3244'
Byte arrays support most of the methods of string types, such asstartswith()
/endswith()
,find()
/rfind()
,and some of the methods of lists, such asappend()
,pop()
, andreverse()
.
>>>b=bytearray('ABC')>>>b.append('d')>>>b.append(ord('e'))>>>bbytearray(b'ABCde')
There's also a corresponding C API, withPyByteArray_FromObject()
,PyByteArray_FromStringAndSize()
,and various other functions.
也參考
- PEP 3112 - Bytes literals in Python 3000
PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes.
PEP 3116:新 I/O 函式庫¶
Python's built-in file objects support a number of methods, butfile-like objects don't necessarily support all of them. Objects thatimitate files usually supportread()
andwrite()
, but theymay not supportreadline()
, for example. Python 3.0 introducesa layered I/O library in theio
module that separates bufferingand text-handling features from the fundamental read and writeoperations.
There are three levels of abstract base classes provided bytheio
module:
RawIOBase
defines raw I/O operations:read()
,readinto()
,write()
,seek()
,tell()
,truncate()
,andclose()
.Most of the methods of this class will often map to a single system call.There are alsoreadable()
,writable()
, andseekable()
methods for determining what operations a given object will allow.Python 3.0 has concrete implementations of this class for files andsockets, but Python 2.6 hasn't restructured its file and socket objectsin this way.
BufferedIOBase
is an abstract base class thatbuffers data in memory to reduce the number ofsystem calls used, making I/O processing more efficient.It supports all of the methods ofRawIOBase
,and adds araw
attribute holding the underlying raw object.There are five concrete classes implementing this ABC.
BufferedWriter
andBufferedReader
are for objectsthat support write-only or read-only usage that have aseek()
method for random access.BufferedRandom
objects supportread and write access upon the same underlying stream, andBufferedRWPair
is for objects such as TTYs that have bothread and write operations acting upon unconnected streams of data.TheBytesIO
class supports reading, writing, and seekingover an in-memory buffer.TextIOBase
: Provides functions for reading and writingstrings (remember, strings will be Unicode in Python 3.0),and supportinguniversal newlines.TextIOBase
definesthereadline()
method and supports iteration uponobjects.There are two concrete implementations.
TextIOWrapper
wraps a buffered I/O object, supporting all of the methods fortext I/O and adding abuffer
attribute for accessto the underlying object.StringIO
simply bufferseverything in memory without ever writing anything to disk.(In Python 2.6,
io.StringIO
is implemented inpure Python, so it's pretty slow. You should therefore stick with theexistingStringIO
module orcStringIO
for now. At somepoint Python 3.0'sio
module will be rewritten into C for speed,and perhaps the C implementation will be backported to the 2.x releases.)
In Python 2.6, the underlying implementations haven't beenrestructured to build on top of theio
module's classes. Themodule is being provided to make it easier to write code that'sforward-compatible with 3.0, and to save developers the effort of writingtheir own implementations of buffering and text I/O.
也參考
- PEP 3116 - New I/O
PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum.Code by Guido van Rossum, Georg Brandl, Walter Doerwald,Jeremy Hylton, Martin von Löwis, Tony Lownds, and others.
PEP 3118:修訂緩衝協定¶
The buffer protocol is a C-level API that lets Python typesexchange pointers into their internal representations. Amemory-mapped file can be viewed as a buffer of characters, forexample, and this lets another module such asre
treat memory-mapped files as a string of characters to be searched.
The primary users of the buffer protocol are numeric-processingpackages such as NumPy, which expose the internal representationof arrays so that callers can write data directly into an array insteadof going through a slower API. This PEP updates the buffer protocol in light of experiencefrom NumPy development, adding a number of new featuressuch as indicating the shape of an array or locking a memory region.
The most important new C API function isPyObject_GetBuffer(PyObject*obj,Py_buffer*view,intflags)
, whichtakes an object and a set of flags, and fills in thePy_buffer
structure with informationabout the object's memory representation. Objectscan use this operation to lock memory in placewhile an external caller could be modifying the contents,so there's a correspondingPyBuffer_Release(Py_buffer*view)
toindicate that the external caller is done.
Theflags argument toPyObject_GetBuffer()
specifiesconstraints upon the memory returned. Some examples are:
PyBUF_WRITABLE
indicates that the memory must be writable.PyBUF_LOCK
requests a read-only or exclusive lock on the memory.PyBUF_C_CONTIGUOUS
andPyBUF_F_CONTIGUOUS
requests a C-contiguous (last dimension varies the fastest) orFortran-contiguous (first dimension varies the fastest) array layout.
Two new argument codes forPyArg_ParseTuple()
,s*
andz*
, return locked buffer objects for a parameter.
也參考
- PEP 3118 - Revising the buffer protocol
PEP written by Travis Oliphant and Carl Banks; implemented byTravis Oliphant.
PEP 3119: Abstract Base Classes¶
Some object-oriented languages such as Java support interfaces,declaring that a class has a given set of methods or supports a givenaccess protocol. Abstract Base Classes (or ABCs) are an equivalentfeature for Python. The ABC support consists of anabc
modulecontaining a metaclass calledABCMeta
, special handling ofthis metaclass by theisinstance()
andissubclass()
builtins, and a collection of basic ABCs that the Python developersthink will be widely useful. Future versions of Python will probablyadd more ABCs.
Let's say you have a particular class and wish to know whether it supportsdictionary-style access. The phrase "dictionary-style" is vague, however.It probably means that accessing items withobj[1]
works.Does it imply that setting items withobj[2]=value
works?Or that the object will havekeys()
,values()
, anditems()
methods? What about the iterative variants such asiterkeys()
?copy()
andupdate()
? Iterating over the object withiter()
?
The Python 2.6collections
module includes a number ofdifferent ABCs that represent these distinctions.Iterable
indicates that a class defines__iter__()
, andContainer
means the class defines a__contains__()
method and therefore supportsxiny
expressions. The basicdictionary interface of getting items, setting items, andkeys()
,values()
, anditems()
, is defined by theMutableMapping
ABC.
You can derive your own classes from a particular ABCto indicate they support that ABC's interface:
importcollectionsclassStorage(collections.MutableMapping):...
Alternatively, you could write the class without deriving fromthe desired ABC and instead register the class bycalling the ABC'sregister()
method:
importcollectionsclassStorage:...collections.MutableMapping.register(Storage)
For classes that you write, deriving from the ABC is probably clearer.Theregister()
method is useful when you've written a newABC that can describe an existing type or class, or if you wantto declare that some third-party class implements an ABC.For example, if you defined aPrintableType
ABC,it's legal to do:
# 註冊 Python 的型別PrintableType.register(int)PrintableType.register(float)PrintableType.register(str)
Classes should obey the semantics specified by an ABC, butPython can't check this; it's up to the class author tounderstand the ABC's requirements and to implement the code accordingly.
To check whether an object supports a particular interface, you cannow write:
deffunc(d):ifnotisinstance(d,collections.MutableMapping):raiseValueError("Mapping object expected, not%r"%d)
Don't feel that you must now begin writing lots of checks as in theabove example. Python has a strong tradition of duck-typing, whereexplicit type-checking is never done and code simply calls methods onan object, trusting that those methods will be there and raising anexception if they aren't. Be judicious in checking for ABCs and onlydo it where it's absolutely necessary.
You can write your own ABCs by usingabc.ABCMeta
as themetaclass in a class definition:
fromabcimportABCMeta,abstractmethodclassDrawable():__metaclass__=ABCMeta@abstractmethoddefdraw(self,x,y,scale=1.0):passdefdraw_doubled(self,x,y):self.draw(x,y,scale=2.0)classSquare(Drawable):defdraw(self,x,y,scale):...
In theDrawable
ABC above, thedraw_doubled()
methodrenders the object at twice its size and can be implemented in termsof other methods described inDrawable
. Classes implementingthis ABC therefore don't need to provide their own implementationofdraw_doubled()
, though they can do so. An implementationofdraw()
is necessary, though; the ABC can't providea useful generic implementation.
You can apply the@abstractmethod
decorator to methods such asdraw()
that must be implemented; Python will then raise anexception for classes that don't define the method.Note that the exception is only raised when you actuallytry to create an instance of a subclass lacking the method:
>>>classCircle(Drawable):...pass...>>>c=Circle()Traceback (most recent call last): File"<stdin>", line1, in<module>TypeError:Can't instantiate abstract class Circle with abstract methods draw>>>
Abstract data attributes can be declared using the@abstractproperty
decorator:
fromabcimportabstractproperty...@abstractpropertydefreadonly(self):returnself._x
Subclasses must then define areadonly()
property.
也參考
- PEP 3119 - Introducing Abstract Base Classes
PEP written by Guido van Rossum and Talin.Implemented by Guido van Rossum.Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.
PEP 3127: Integer Literal Support and Syntax¶
Python 3.0 changes the syntax for octal (base-8) integer literals,prefixing them with "0o" or "0O" instead of a leading zero, and addssupport for binary (base-2) integer literals, signalled by a "0b" or"0B" prefix.
Python 2.6 doesn't drop support for a leading 0 signallingan octal number, but it does add support for "0o" and "0b":
>>>0o21,2*8+1(17, 17)>>>0b10111147
Theoct()
builtin still returns numbersprefixed with a leading zero, and a newbin()
builtin returns the binary representation for a number:
>>>oct(42)'052'>>>future_builtins.oct(42)'0o52'>>>bin(173)'0b10101101'
Theint()
andlong()
builtins will now accept the "0o"and "0b" prefixes when base-8 or base-2 are requested, or when thebase argument is zero (signalling that the base used should bedetermined from the string):
>>>int('0o52',0)42>>>int('1101',2)13>>>int('0b1101',2)13>>>int('0b1101',0)13
也參考
- PEP 3127 - Integer Literal Support and Syntax
PEP written by Patrick Maupin; backported to 2.6 byEric Smith.
PEP 3129: Class Decorators¶
Decorators have been extended from functions to classes. It's now legal towrite:
@foo@barclassA:pass
這等價於:
classA:passA=foo(bar(A))
也參考
- PEP 3129 - Class Decorators
由 Collin Winter 撰寫 PEP。
PEP 3141: A Type Hierarchy for Numbers¶
Python 3.0 adds several abstract base classes for numeric typesinspired by Scheme's numeric tower. These classes were backported to2.6 as thenumbers
module.
The most general ABC isNumber
. It defines no operations atall, and only exists to allow checking if an object is a number bydoingisinstance(obj,Number)
.
Complex
is a subclass ofNumber
. Complex numberscan undergo the basic operations of addition, subtraction,multiplication, division, and exponentiation, and you can retrieve thereal and imaginary parts and obtain a number's conjugate. Python's built-incomplex type is an implementation ofComplex
.
Real
further derives fromComplex
, and addsoperations that only work on real numbers:floor()
,trunc()
,rounding, taking the remainder mod N, floor division,and comparisons.
Rational
numbers derive fromReal
, havenumerator
anddenominator
properties, and can beconverted to floats. Python 2.6 adds a simple rational-number class,Fraction
, in thefractions
module. (It's calledFraction
instead ofRational
to avoida name clash withnumbers.Rational
.)
Integral
numbers derive fromRational
, andcan be shifted left and right with<<
and>>
,combined using bitwise operations such as&
and|
,and can be used as array indexes and slice boundaries.
In Python 3.0, the PEP slightly redefines the existing builtinsround()
,math.floor()
,math.ceil()
, and adds a newone,math.trunc()
, that's been backported to Python 2.6.math.trunc()
rounds toward zero, returning the closestIntegral
that's between the function's argument and zero.
也參考
- PEP 3141 - A Type Hierarchy for Numbers
由 Jeffrey Yasskin 撰寫 PEP。
Scheme's numerical tower, from the Guile manual.
Scheme's number datatypes from the R5RS Scheme specification.
Thefractions
Module¶
To fill out the hierarchy of numeric types, thefractions
module provides a rational-number class. Rational numbers store theirvalues as a numerator and denominator forming a fraction, and canexactly represent numbers such as2/3
that floating-point numberscan only approximate.
TheFraction
constructor takes twoIntegral
valuesthat will be the numerator and denominator of the resulting fraction.
>>>fromfractionsimportFraction>>>a=Fraction(2,3)>>>b=Fraction(2,5)>>>float(a),float(b)(0.66666666666666663, 0.40000000000000002)>>>a+bFraction(16, 15)>>>a/bFraction(5, 3)
For converting floating-point numbers to rationals,the float type now has anas_integer_ratio()
method that returnsthe numerator and denominator for a fraction that evaluates to the samefloating-point value:
>>>(2.5).as_integer_ratio()(5, 2)>>>(3.1415).as_integer_ratio()(7074029114692207L, 2251799813685248L)>>>(1./3).as_integer_ratio()(6004799503160661L, 18014398509481984L)
Note that values that can only be approximated by floating-pointnumbers, such as 1./3, are not simplified to the number beingapproximated; the fraction attempts to match the floating-point valueexactly.
Thefractions
module is based upon an implementation by SjoerdMullender that was in Python'sDemo/classes/
directory for along time. This implementation was significantly updated by JeffreyYasskin.
其他語言更動¶
Some smaller changes made to the core Python language are:
Directories and zip archives containing a
__main__.py
filecan now be executed directly by passing their name to theinterpreter. The directory or zip archive is automatically insertedas the first entry in sys.path. (Suggestion and initial patch byAndy Chu, subsequently revised by Phillip J. Eby and Nick Coghlan;bpo-1739468.)The
hasattr()
function was catching and ignoring all errors,under the assumption that they meant a__getattr__()
methodwas failing somehow and the return value ofhasattr()
wouldtherefore beFalse
. This logic shouldn't be applied toKeyboardInterrupt
andSystemExit
, however; Python 2.6will no longer discard such exceptions whenhasattr()
encounters them. (Fixed by Benjamin Peterson;bpo-2196.)When calling a function using the
**
syntax to provide keywordarguments, you are no longer required to use a Python dictionary;any mapping will now work:>>>deff(**kw):...printsorted(kw)...>>>ud=UserDict.UserDict()>>>ud['a']=1>>>ud['b']='string'>>>f(**ud)['a', 'b']
(由 Alexander Belopolsky 所貢獻;bpo-1686487。)
It's also become legal to provide keyword arguments after a
*args
argumentto a function call.>>>deff(*args,**kw):...printargs,kw...>>>f(1,2,3,*(4,5,6),keyword=13)(1, 2, 3, 4, 5, 6) {'keyword': 13}
Previously this would have been a syntax error.(Contributed by Amaury Forgeot d'Arc;bpo-3473.)
A new builtin,
next(iterator,[default])
returns the next itemfrom the specified iterator. If thedefault argument is supplied,it will be returned ifiterator has been exhausted; otherwise,theStopIteration
exception will be raised. (Backportedinbpo-2719.)Tuples now have
index()
andcount()
methods matching thelist type'sindex()
andcount()
methods:>>>t=(0,1,2,3,4,0,1,2)>>>t.index(3)3>>>t.count(0)2
(由 Raymond Hettinger 所貢獻。)
The built-in types now have improved support for extended slicing syntax,accepting various combinations of
(start,stop,step)
.Previously, the support was partial and certain corner cases wouldn't work.(Implemented by Thomas Wouters.)Properties now have three attributes,
getter
,setter
anddeleter
, that are decorators providing useful shortcutsfor adding a getter, setter or deleter function to an existingproperty. You would use them like this:classC(object):@propertydefx(self):returnself._x@x.setterdefx(self,value):self._x=value@x.deleterdefx(self):delself._xclassD(C):@C.x.getterdefx(self):returnself._x*2@x.setterdefx(self,value):self._x=value/2
Several methods of the built-in set types now accept multiple iterables:
intersection()
,intersection_update()
,union()
,update()
,difference()
anddifference_update()
.>>>s=set('1234567890')>>>s.intersection('abc123','cdf246')# Intersection between all inputsset(['2'])>>>s.difference('246','789')set(['1', '0', '3', '5'])
(由 Raymond Hettinger 所貢獻。)
Many floating-point features were added. The
float()
functionwill now turn the stringnan
into anIEEE 754 Not A Number value, and+inf
and-inf
intopositive or negative infinity. This works on any platform withIEEE 754 semantics. (Contributed by Christian Heimes;bpo-1635.)Other functions in the
math
module,isinf()
andisnan()
, return true if their floating-point argument isinfinite or Not A Number. (bpo-1640)Conversion functions were added to convert floating-point numbersinto hexadecimal strings (bpo-3008). These functionsconvert floats to and from a string representation withoutintroducing rounding errors from the conversion between decimal andbinary. Floats have a
hex()
method that returns a stringrepresentation, and thefloat.fromhex()
method converts a stringback into a number:>>>a=3.75>>>a.hex()'0x1.e000000000000p+1'>>>float.fromhex('0x1.e000000000000p+1')3.75>>>b=1./3>>>b.hex()'0x1.5555555555555p-2'
A numerical nicety: when creating a complex number from two floatson systems that support signed zeros (-0 and +0), the
complex()
constructor will now preserve the signof the zero. (Fixed by Mark T. Dickinson;bpo-1507.)Classes that inherit a
__hash__()
method from a parent classcan set__hash__=None
to indicate that the class isn'thashable. This will makehash(obj)
raise aTypeError
and the class will not be indicated as implementing theHashable
ABC.You should do this when you've defined a
__cmp__()
or__eq__()
method that compares objects by their value ratherthan by identity. All objects have a default hash method that usesid(obj)
as the hash value. There's no tidy way to remove the__hash__()
method inherited from a parent class, soassigningNone
was implemented as an override. At theC level, extensions can settp_hash
toPyObject_HashNotImplemented()
.(Fixed by Nick Coghlan and Amaury Forgeot d'Arc;bpo-2235.)The
GeneratorExit
exception now subclassesBaseException
instead ofException
. This meansthat an exception handler that doesexceptException:
will not inadvertently catchGeneratorExit
.(Contributed by Chad Austin;bpo-1537.)Generator objects now have a
gi_code
attribute that refers tothe original code object backing the generator.(Contributed by Collin Winter;bpo-1473257.)The
compile()
built-in function now accepts keyword argumentsas well as positional parameters. (Contributed by Thomas Wouters;bpo-1444529.)The
complex()
constructor now accepts strings containingparenthesized complex numbers, meaning thatcomplex(repr(cplx))
will now round-trip values. For example,complex('(3+4j)')
now returns the value (3+4j). (bpo-1491866)The string
translate()
method now acceptsNone
as thetranslation table parameter, which is treated as the identitytransformation. This makes it easier to carry out operationsthat only delete characters. (Contributed by Bengt Richter andimplemented by Raymond Hettinger;bpo-1193128.)The built-in
dir()
function now checks for a__dir__()
method on the objects it receives. This method must return a listof strings containing the names of valid attributes for the object,and lets the object control the value thatdir()
produces.Objects that have__getattr__()
or__getattribute__()
methods can use this to advertise pseudo-attributes they will honor.(bpo-1591665)Instance method objects have new attributes for the object and functioncomprising the method; the new synonym for
im_self
is__self__
, andim_func
is also available as__func__
.The old names are still supported in Python 2.6, but are gone in 3.0.An obscure change: when you use the
locals()
function inside aclass
statement, the resulting dictionary no longer returns freevariables. (Free variables, in this case, are variables referenced in theclass
statement that aren't attributes of the class.)
最佳化¶
The
warnings
module has been rewritten in C. This makesit possible to invoke warnings from the parser, and may alsomake the interpreter's startup faster.(Contributed by Neal Norwitz and Brett Cannon;bpo-1631171.)Type objects now have a cache of methods that can reducethe work required to find the correct method implementationfor a particular class; once cached, the interpreter doesn't need totraverse base classes to figure out the right method to call.The cache is cleared if a base class or the class itself is modified,so the cache should remain correct even in the face of Python's dynamicnature.(Original optimization implemented by Armin Rigo, updated forPython 2.6 by Kevin Jacobs;bpo-1700288.)
By default, this change is only applied to types that are included withthe Python core. Extension modules may not necessarily be compatible withthis cache,so they must explicitly add
Py_TPFLAGS_HAVE_VERSION_TAG
to the module'stp_flags
field to enable the method cache.(To be compatible with the method cache, the extension module's codemust not directly access and modify thetp_dict
member ofany of the types it implements. Most modules don't do this,but it's impossible for the Python interpreter to determine that.Seebpo-1878 for some discussion.)Function calls that use keyword arguments are significantly fasterby doing a quick pointer comparison, usually saving the time of afull string comparison. (Contributed by Raymond Hettinger, after aninitial implementation by Antoine Pitrou;bpo-1819.)
All of the functions in the
struct
module have been rewritten inC, thanks to work at the Need For Speed sprint.(Contributed by Raymond Hettinger.)Some of the standard built-in types now set a bit in their typeobjects. This speeds up checking whether an object is a subclass ofone of these types. (Contributed by Neal Norwitz.)
Unicode strings now use faster code for detectingwhitespace and line breaks; this speeds up the
split()
methodby about 25% andsplitlines()
by 35%.(Contributed by Antoine Pitrou.) Memory usage is reducedby using pymalloc for the Unicode string's data.The
with
statement now stores the__exit__()
method on the stack,producing a small speedup. (Implemented by Jeffrey Yasskin.)To reduce memory usage, the garbage collector will now clear internalfree lists when garbage-collecting the highest generation of objects.This may return memory to the operating system sooner.
Interpreter Changes¶
Two command-line options have been reserved for use by other Pythonimplementations. The-J
switch has been reserved for use byJython for Jython-specific options, such as switches that are passed tothe underlying JVM.-X
has been reserved for optionsspecific to a particular implementation of Python such as CPython,Jython, or IronPython. If either option is used with Python 2.6, theinterpreter will report that the option isn't currently used.
Python can now be prevented from writing.pyc
or.pyo
files by supplying the-B
switch to the Python interpreter,or by setting thePYTHONDONTWRITEBYTECODE
environmentvariable before running the interpreter. This setting is available toPython programs as thesys.dont_write_bytecode
variable, andPython code can change the value to modify the interpreter'sbehaviour. (Contributed by Neal Norwitz and Georg Brandl.)
The encoding used for standard input, output, and standard error canbe specified by setting thePYTHONIOENCODING
environmentvariable before running the interpreter. The value should be a stringin the form<encoding>
or<encoding>:<errorhandler>
.Theencoding part specifies the encoding's name, e.g.utf-8
orlatin-1
; the optionalerrorhandler part specifieswhat to do with characters that can't be handled by the encoding,and should be one of "error", "ignore", or "replace". (Contributedby Martin von Löwis.)
New and Improved Modules¶
As in every release, Python's standard library received a number ofenhancements and bug fixes. Here's a partial list of the most notablechanges, sorted alphabetically by module name. Consult theMisc/NEWS
file in the source tree for a more complete list ofchanges, or look through the Subversion logs for all the details.
The
asyncore
andasynchat
modules arebeing actively maintained again, and a number of patches and bugfixeswere applied. (Maintained by Josiah Carlson; seebpo-1736190 forone patch.)The
bsddb
module also has a new maintainer, Jesús Cea Avión, and the packageis now available as a standalone package. The web page for the package iswww.jcea.es/programacion/pybsddb.htm.The plan is to remove the package from the standard libraryin Python 3.0, because its pace of releases is much more frequent thanPython's.The
bsddb.dbshelve
module now uses the highest pickling protocolavailable, instead of restricting itself to protocol 1.(Contributed by W. Barnes.)The
cgi
module will now read variables from the query stringof an HTTP POST request. This makes it possible to use form actionswith URLs that include query strings such as"/cgi-bin/add.py?category=1". (Contributed by Alexandre Fiori andNubis;bpo-1817.)The
parse_qs()
andparse_qsl()
functions have beenrelocated from thecgi
module to theurlparse
module.The versions still available in thecgi
module willtriggerPendingDeprecationWarning
messages in 2.6(bpo-600362).The
cmath
module underwent extensive revision,contributed by Mark Dickinson and Christian Heimes.Five new functions were added:polar()
converts a complex number to polar form, returningthe modulus and argument of the complex number.rect()
does the opposite, turning a modulus, argument pairback into the corresponding complex number.phase()
returns the argument (also called the angle) of a complexnumber.isnan()
returns True if eitherthe real or imaginary part of its argument is a NaN.isinf()
returns True if either the real or imaginary part ofits argument is infinite.
The revisions also improved the numerical soundness of the
cmath
module. For all functions, the real and imaginaryparts of the results are accurate to within a few units of leastprecision (ulps) whenever possible. Seebpo-1381 for thedetails. The branch cuts forasinh()
,atanh()
: andatan()
have also been corrected.The tests for the module have been greatly expanded; nearly 2000 newtest cases exercise the algebraic functions.
On IEEE 754 platforms, the
cmath
module now handles IEEE 754special values and floating-point exceptions in a manner consistentwith Annex 'G' of the C99 standard.A new data type in the
collections
module:namedtuple(typename,fieldnames)
is a factory function that creates subclasses of the standard tuplewhose fields are accessible by name as well as index. For example:>>>var_type=collections.namedtuple('variable',...'id name type size')>>># Names are separated by spaces or commas.>>># 'id, name, type, size' would also work.>>>var_type._fields('id', 'name', 'type', 'size')>>>var=var_type(1,'frequency','int',4)>>>printvar[0],var.id# Equivalent1 1>>>printvar[2],var.type# Equivalentint int>>>var._asdict(){'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}>>>v2=var._replace(name='amplitude')>>>v2variable(id=1, name='amplitude', type='int', size=4)
Several places in the standard library that returned tuples havebeen modified to return
namedtuple()
instances. For example,theDecimal.as_tuple()
method now returns a named tuple withsign
,digits
, andexponent
fields.(由 Raymond Hettinger 所貢獻。)
Another change to the
collections
module is that thedeque
type now supports an optionalmaxlen parameter;if supplied, the deque's size will be restricted to no morethanmaxlen items. Adding more items to a full deque causesold items to be discarded.>>>fromcollectionsimportdeque>>>dq=deque(maxlen=3)>>>dqdeque([], maxlen=3)>>>dq.append(1);dq.append(2);dq.append(3)>>>dqdeque([1, 2, 3], maxlen=3)>>>dq.append(4)>>>dqdeque([2, 3, 4], maxlen=3)
(由 Raymond Hettinger 所貢獻。)
The
Cookie
module'sMorsel
objects now support anhttponly
attribute. In some browsers. cookies with this attributeset cannot be accessed or manipulated by JavaScript code.(Contributed by Arvin Schnell;bpo-1638033.)A new window method in the
curses
module,chgat()
, changes the display attributes for a certain number ofcharacters on a single line. (Contributed by Fabian Kreutz.)# Boldface text starting at y=0,x=21# and affecting the rest of the line.stdscr.chgat(0,21,curses.A_BOLD)
The
Textbox
class in thecurses.textpad
modulenow supports editing in insert mode as well as overwrite mode.Insert mode is enabled by supplying a true value for theinsert_modeparameter when creating theTextbox
instance.The
datetime
module'sstrftime()
methods now support a%f
format code that expands to the number of microseconds in theobject, zero-padded onthe left to six places. (Contributed by Skip Montanaro;bpo-1158.)The
decimal
module was updated to version 1.66 ofthe General Decimal Specification. New featuresinclude some methods for some basic mathematical functions such asexp()
andlog10()
:>>>Decimal(1).exp()Decimal("2.718281828459045235360287471")>>>Decimal("2.7182818").ln()Decimal("0.9999999895305022877376682436")>>>Decimal(1000).log10()Decimal("3")
The
as_tuple()
method ofDecimal
objects now returns anamed tuple withsign
,digits
, andexponent
fields.(Implemented by Facundo Batista and Mark Dickinson. Named tuplesupport added by Raymond Hettinger.)
The
difflib
module'sSequenceMatcher
classnow returns named tuples representing matches,witha
,b
, andsize
attributes.(Contributed by Raymond Hettinger.)An optional
timeout
parameter, specifying a timeout measured inseconds, was added to theftplib.FTP
class constructor aswell as theconnect()
method. (Added by Facundo Batista.)Also, theFTP
class'sstorbinary()
andstorlines()
now take an optionalcallback parameter thatwill be called with each block of data after the data has been sent.(Contributed by Phil Schwartz;bpo-1221598.)The
reduce()
built-in function is also available in thefunctools
module. In Python 3.0, the builtin has beendropped andreduce()
is only available fromfunctools
;currently there are no plans to drop the builtin in the 2.x series.(Patched by Christian Heimes;bpo-1739906.)When possible, the
getpass
module will now use/dev/tty
to print a prompt message and read the password,falling back to standard error and standard input. If thepassword may be echoed to the terminal, a warning is printed beforethe prompt is displayed. (Contributed by Gregory P. Smith.)The
glob.glob()
function can now return Unicode filenames ifa Unicode path was used and Unicode filenames are matched within thedirectory. (bpo-1001604)A new function in the
heapq
module,merge(iter1,iter2,...)
,takes any number of iterables returning data in sortedorder, and returns a new generator that returns the contents of allthe iterators, also in sorted order. For example:>>>list(heapq.merge([1,3,5,9],[2,8,16]))[1, 2, 3, 5, 8, 9, 16]
Another new function,
heappushpop(heap,item)
,pushesitem ontoheap, then pops off and returns the smallest item.This is more efficient than making a call toheappush()
and thenheappop()
.heapq
is now implemented to only use less-than comparison,instead of the less-than-or-equal comparison it previously used.This makesheapq
's usage of a type match thelist.sort()
method.(Contributed by Raymond Hettinger.)An optional
timeout
parameter, specifying a timeout measured inseconds, was added to thehttplib.HTTPConnection
andHTTPSConnection
class constructors. (Added by FacundoBatista.)Most of the
inspect
module's functions, such asgetmoduleinfo()
andgetargs()
, now return named tuples.In addition to behaving like tuples, the elements of the return valuecan also be accessed as attributes.(Contributed by Raymond Hettinger.)Some new functions in the module include
isgenerator()
,isgeneratorfunction()
,andisabstract()
.The
itertools
module gained several new functions.izip_longest(iter1,iter2,...[,fillvalue])
makes tuples fromeach of the elements; if some of the iterables are shorter thanothers, the missing values are set tofillvalue. For example:>>>tuple(itertools.izip_longest([1,2,3],[1,2,3,4,5]))((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))
product(iter1,iter2,...,[repeat=N])
returns the Cartesian productof the supplied iterables, a set of tuples containingevery possible combination of the elements returned from each iterable.>>>list(itertools.product([1,2,3],[4,5,6]))[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
The optionalrepeat keyword argument is used for taking theproduct of an iterable or a set of iterables with themselves,repeatedN times. With a single iterable argument,N-tuplesare returned:
>>>list(itertools.product([1,2],repeat=3))[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
With two iterables,2N-tuples are returned.
>>>list(itertools.product([1,2],[3,4],repeat=2))[(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4), (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4), (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4), (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
combinations(iterable,r)
returns sub-sequences of lengthr fromthe elements ofiterable.>>>list(itertools.combinations('123',2))[('1', '2'), ('1', '3'), ('2', '3')]>>>list(itertools.combinations('123',3))[('1', '2', '3')]>>>list(itertools.combinations('1234',3))[('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'), ('2', '3', '4')]
permutations(iter[,r])
returns all the permutations of lengthr ofthe iterable's elements. Ifr is not specified, it will default to thenumber of elements produced by the iterable.>>>list(itertools.permutations([1,2,3,4],2))[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
itertools.chain(*iterables)
is an existing function initertools
that gained a new constructor in Python 2.6.itertools.chain.from_iterable(iterable)
takes a singleiterable that should return other iterables.chain()
willthen return all the elements of the first iterable, thenall the elements of the second, and so on.>>>list(itertools.chain.from_iterable([[1,2,3],[4,5,6]]))[1, 2, 3, 4, 5, 6]
(All contributed by Raymond Hettinger.)
The
logging
module'sFileHandler
classand its subclassesWatchedFileHandler
,RotatingFileHandler
,andTimedRotatingFileHandler
nowhave an optionaldelay parameter to their constructors. Ifdelayis true, opening of the log file is deferred until the firstemit()
call is made. (Contributed by Vinay Sajip.)TimedRotatingFileHandler
also has autc constructorparameter. If the argument is true, UTC time will be usedin determining when midnight occurs and in generating filenames;otherwise local time will be used.Several new functions were added to the
math
module:isinf()
andisnan()
determine whether a given floatis a (positive or negative) infinity or a NaN (Not a Number), respectively.copysign()
copies the sign bit of an IEEE 754 number,returning the absolute value ofx combined with the sign bit ofy. For example,math.copysign(1,-0.0)
returns -1.0.(Contributed by Christian Heimes.)factorial()
computes the factorial of a number.(Contributed by Raymond Hettinger;bpo-2138.)fsum()
adds up the stream of numbers from an iterable,and is careful to avoid loss of precision through using partial sums.(Contributed by Jean Brouwers, Raymond Hettinger, and Mark Dickinson;bpo-2819.)acosh()
,asinh()
andatanh()
compute the inverse hyperbolic functions.log1p()
returns the natural logarithm of1+x(basee).trunc()
rounds a number toward zero, returning the closestIntegral
that's between the function's argument and zero.Added as part of the backport ofPEP 3141's type hierarchy for numbers.
The
math
module has been improved to give more consistentbehaviour across platforms, especially with respect to handling offloating-point exceptions and IEEE 754 special values.Whenever possible, the module follows the recommendations of the C99standard about 754's special values. For example,
sqrt(-1.)
should now give aValueError
across almost all platforms,whilesqrt(float('NaN'))
should return a NaN on all IEEE 754platforms. Where Annex 'F' of the C99 standard recommends signaling'divide-by-zero' or 'invalid', Python will raiseValueError
.Where Annex 'F' of the C99 standard recommends signaling 'overflow',Python will raiseOverflowError
. (Seebpo-711019 andbpo-1640.)(由 Christian Heimes 和 Mark Dickinson 所貢獻。)
mmap
objects now have arfind()
method that searches for asubstring beginning at the end of the string and searchingbackwards. Thefind()
method also gained anend parametergiving an index at which to stop searching.(Contributed by John Lenton.)The
operator
module gained amethodcaller()
function that takes a name and an optionalset of arguments, returning a callable that will callthe named function on any arguments passed to it. For example:>>># Equivalent to lambda s: s.replace('old', 'new')>>>replacer=operator.methodcaller('replace','old','new')>>>replacer('old wine in old bottles')'new wine in new bottles'
(經 Gregory Petrosyan 建議後由 Georg Brandl 所貢獻。)
The
attrgetter()
function now accepts dotted names and performsthe corresponding attribute lookups:>>>inst_name=operator.attrgetter(...'__class__.__name__')>>>inst_name('')'str'>>>inst_name(help)'_Helper'
(經 Barry Warsaw 建議後由 Georg Brandl 所貢獻。)
The
os
module now wraps several new system calls.fchmod(fd,mode)
andfchown(fd,uid,gid)
change the modeand ownership of an opened file, andlchmod(path,mode)
changesthe mode of a symlink. (Contributed by Georg Brandl and ChristianHeimes.)chflags()
andlchflags()
are wrappers for thecorresponding system calls (where they're available), changing theflags set on a file. Constants for the flag values are defined inthestat
module; some possible values includeUF_IMMUTABLE
to signal the file may not be changed andUF_APPEND
to indicate that data can only be appended to thefile. (Contributed by M. Levinson.)os.closerange(low,high)
efficiently closes all file descriptorsfromlow tohigh, ignoring any errors and not includinghigh itself.This function is now used by thesubprocess
module to make startingprocesses faster. (Contributed by Georg Brandl;bpo-1663329.)The
os.environ
object'sclear()
method will now unset theenvironment variables usingos.unsetenv()
in addition to clearingthe object's keys. (Contributed by Martin Horcicka;bpo-1181.)The
os.walk()
function now has afollowlinks
parameter. Ifset to True, it will follow symlinks pointing to directories andvisit the directory's contents. For backward compatibility, theparameter's default value is false. Note that the function can fallinto an infinite recursion if there's a symlink that points to aparent directory. (bpo-1273829)In the
os.path
module, thesplitext()
functionhas been changed to not split on leading period characters.This produces better results when operating on Unix's dot-files.For example,os.path.splitext('.ipython')
now returns('.ipython','')
instead of('','.ipython')
.(bpo-1115886)A new function,
os.path.relpath(path,start='.')
, returns a relative pathfrom thestart
path, if it's supplied, or from the currentworking directory to the destinationpath
. (Contributed byRichard Barran;bpo-1339796.)On Windows,
os.path.expandvars()
will now expand environment variablesgiven in the form "%var%", and "~user" will be expanded into theuser's home directory path. (Contributed by Josiah Carlson;bpo-957650.)The Python debugger provided by the
pdb
modulegained a new command: "run" restarts the Python program being debuggedand can optionally take new command-line arguments for the program.(Contributed by Rocky Bernstein;bpo-1393667.)The
pdb.post_mortem()
function, used to begin debugging atraceback, will now use the traceback returned bysys.exc_info()
if no traceback is supplied. (Contributed by Facundo Batista;bpo-1106316.)The
pickletools
module now has anoptimize()
functionthat takes a string containing a pickle and removes some unusedopcodes, returning a shorter pickle that contains the same data structure.(Contributed by Raymond Hettinger.)A
get_data()
function was added to thepkgutil
module that returns the contents of resource files includedwith an installed Python package. For example:>>>importpkgutil>>>printpkgutil.get_data('test','exception_hierarchy.txt')BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StandardError ...
(由 Paul Moore 貢獻;bpo-2439。)
The
pyexpat
module'sParser
objects now allow settingtheirbuffer_size
attribute to change the size of the bufferused to hold character data.(Contributed by Achim Gaedke;bpo-1137.)The
Queue
module now provides queue variants that retrieve entriesin different orders. ThePriorityQueue
class storesqueued items in a heap and retrieves them in priority order,andLifoQueue
retrieves the most recently added entries first,meaning that it behaves like a stack.(Contributed by Raymond Hettinger.)The
random
module'sRandom
objects cannow be pickled on a 32-bit system and unpickled on a 64-bitsystem, and vice versa. Unfortunately, this change also meansthat Python 2.6'sRandom
objects can't be unpickled correctlyon earlier versions of Python.(Contributed by Shawn Ligocki;bpo-1727780.)The new
triangular(low,high,mode)
function returns randomnumbers following a triangular distribution. The returned valuesare betweenlow andhigh, not includinghigh itself, andwithmode as the most frequently occurring valuein the distribution. (Contributed by Wladmir van der Laan andRaymond Hettinger;bpo-1681432.)Long regular expression searches carried out by the
re
module will check for signals being delivered, sotime-consuming searches can now be interrupted.(Contributed by Josh Hoyt and Ralf Schmitt;bpo-846388.)The regular expression module is implemented by compiling bytecodesfor a tiny regex-specific virtual machine. Untrusted codecould create malicious strings of bytecode directly and cause crashes,so Python 2.6 includes a verifier for the regex bytecode.(Contributed by Guido van Rossum from work for Google App Engine;bpo-3487.)
The
rlcompleter
module'sCompleter.complete()
methodwill now ignore exceptions triggered while evaluating a name.(Fixed by Lorenz Quack;bpo-2250.)The
sched
module'sscheduler
instances nowhave a read-onlyqueue
attribute that returns thecontents of the scheduler's queue, represented as a list ofnamed tuples with the fields(time,priority,action,argument)
.(Contributed by Raymond Hettinger;bpo-1861.)The
select
module now has wrapper functionsfor the Linuxepoll()
and BSDkqueue()
system calls.modify()
method was added to the existingpoll
objects;pollobj.modify(fd,eventmask)
takes a file descriptoror file object and an event mask, modifying the recorded event maskfor that file.(Contributed by Christian Heimes;bpo-1657.)The
shutil.copytree()
function now has an optionalignore argumentthat takes a callable object. This callable will receive each directory pathand a list of the directory's contents, and returns a list of names thatwill be ignored, not copied.The
shutil
module also provides anignore_patterns()
function for use with this new parameter.ignore_patterns()
takes an arbitrary number of glob-style patterns and returns acallable that will ignore any files and directories that match anyof these patterns. The following example copies a directory tree,but skips both.svn
directories and Emacs backup files,which have names ending with '~':shutil.copytree('Doc/library','/tmp/library',ignore=shutil.ignore_patterns('*~','.svn'))
(由 Tarek Ziadé 貢獻;bpo-2663。)
Integrating signal handling with GUI handling event loopslike those used by Tkinter or GTk+ has long been a problem; mostsoftware ends up polling, waking up every fraction of a second to checkif any GUI events have occurred.The
signal
module can now make this more efficient.Callingsignal.set_wakeup_fd(fd)
sets a file descriptorto be used; when a signal is received, a byte is written to thatfile descriptor. There's also a C-level function,PySignal_SetWakeupFd()
, for setting the descriptor.Event loops will use this by opening a pipe to create two descriptors,one for reading and one for writing. The writable descriptorwill be passed to
set_wakeup_fd()
, and the readable descriptorwill be added to the list of descriptors monitored by the event loop viaselect()
orpoll()
.On receiving a signal, a byte will be written and the main event loopwill be woken up, avoiding the need to poll.(由 Adam Olsen 貢獻;bpo-1583。)
The
siginterrupt()
function is now available from Python code,and allows changing whether signals can interrupt system calls or not.(Contributed by Ralf Schmitt.)The
setitimer()
andgetitimer()
functions have also beenadded (where they're available).setitimer()
allows setting interval timers that will cause a signal to bedelivered to the process after a specified time, measured inwall-clock time, consumed process time, or combined process+systemtime. (Contributed by Guilherme Polo;bpo-2240.)The
smtplib
module now supports SMTP over SSL thanks to theaddition of theSMTP_SSL
class. This class supports aninterface identical to the existingSMTP
class.(Contributed by Monty Taylor.) Both class constructors also have anoptionaltimeout
parameter that specifies a timeout for theinitial connection attempt, measured in seconds. (Contributed byFacundo Batista.)An implementation of the LMTP protocol (RFC 2033) was also addedto the module. LMTP is used in place of SMTP when transferringe-mail between agents that don't manage a mail queue. (LMTPimplemented by Leif Hedstrom;bpo-957003.)
SMTP.starttls()
now complies withRFC 3207 and forgets anyknowledge obtained from the server not obtained from the TLSnegotiation itself. (Patch contributed by Bill Fenner;bpo-829951.)The
socket
module now supports TIPC (https://tipc.sourceforge.net/),a high-performance non-IP-based protocol designed for use in clusteredenvironments. TIPC addresses are 4- or 5-tuples.(Contributed by Alberto Bertogli;bpo-1646.)A new function,
create_connection()
, takes an address andconnects to it using an optional timeout value, returning theconnected socket object. This function also looks up the address'stype and connects to it using IPv4 or IPv6 as appropriate. Changingyour code to usecreate_connection()
instead ofsocket(socket.AF_INET,...)
may be all that's required to makeyour code work with IPv6.The base classes in the
SocketServer
module now supportcalling ahandle_timeout()
method after a span of inactivityspecified by the server'stimeout
attribute. (Contributedby Michael Pomraning.) Theserve_forever()
methodnow takes an optional poll interval measured in seconds,controlling how often the server will check for a shutdown request.(Contributed by Pedro Werneck and Jeffrey Yasskin;bpo-742598,bpo-1193577.)The
sqlite3
module, maintained by Gerhard Häring,has been updated from version 2.3.2 in Python 2.5 toversion 2.4.1.The
struct
module now supports the C99_Bool type,using the format character'?'
.(Contributed by David Remahl.)The
Popen
objects provided by thesubprocess
modulenow haveterminate()
,kill()
, andsend_signal()
methods.On Windows,send_signal()
only supports theSIGTERM
signal, and all these methods are aliases for the Win32 API functionTerminateProcess()
.(Contributed by Christian Heimes.)A new variable in the
sys
module,float_info
, is anobject containing information derived from thefloat.h
fileabout the platform's floating-point support. Attributes of thisobject includemant_dig
(number of digits in the mantissa),epsilon
(smallest difference between 1.0 and the nextlargest value representable), and several others. (Contributed byChristian Heimes;bpo-1534.)Another new variable,
dont_write_bytecode
, controls whether Pythonwrites any.pyc
or.pyo
files on importing a module.If this variable is true, the compiled files are not written. Thevariable is initially set on start-up by supplying the-B
switch to the Python interpreter, or by setting thePYTHONDONTWRITEBYTECODE
environment variable beforerunning the interpreter. Python code can subsequentlychange the value of this variable to control whether bytecode filesare written or not.(Contributed by Neal Norwitz and Georg Brandl.)Information about the command-line arguments supplied to the Pythoninterpreter is available by reading attributes of a namedtuple available as
sys.flags
. For example, theverbose
attribute is true if Pythonwas executed in verbose mode,debug
is true in debugging mode, etc.These attributes are all read-only.(Contributed by Christian Heimes.)A new function,
getsizeof()
, takes a Python object and returnsthe amount of memory used by the object, measured in bytes. Built-inobjects return correct results; third-party extensions may not,but can define a__sizeof__()
method to return theobject's size.(Contributed by Robert Schuppenies;bpo-2898.)It's now possible to determine the current profiler and tracer functionsby calling
sys.getprofile()
andsys.gettrace()
.(Contributed by Georg Brandl;bpo-1648.)The
tarfile
module now supports POSIX.1-2001 (pax) tarfiles inaddition to the POSIX.1-1988 (ustar) and GNU tar formats that werealready supported. The default format is GNU tar; specify theformat
parameter to open a file using a different format:tar=tarfile.open("output.tar","w",format=tarfile.PAX_FORMAT)
The new
encoding
anderrors
parameters specify an encoding andan error handling scheme for character conversions.'strict'
,'ignore'
, and'replace'
are the three standard ways Python canhandle errors,;'utf-8'
is a special value that replaces bad characters withtheir UTF-8 representation. (Character conversions occur because thePAX format supports Unicode filenames, defaulting to UTF-8 encoding.)The
TarFile.add()
method now accepts anexclude
argument that'sa function that can be used to exclude certain filenames froman archive.The function must take a filename and return true if the fileshould be excluded or false if it should be archived.The function is applied to both the name initially passed toadd()
and to the names of files in recursively added directories.(All changes contributed by Lars Gustäbel).
An optional
timeout
parameter was added to thetelnetlib.Telnet
class constructor, specifying a timeoutmeasured in seconds. (Added by Facundo Batista.)The
tempfile.NamedTemporaryFile
class usually deletesthe temporary file it created when the file is closed. Thisbehaviour can now be changed by passingdelete=False
to theconstructor. (Contributed by Damien Miller;bpo-1537850.)A new class,
SpooledTemporaryFile
, behaves likea temporary file but stores its data in memory until a maximum size isexceeded. On reaching that limit, the contents will be written toan on-disk temporary file. (Contributed by Dustin J. Mitchell.)The
NamedTemporaryFile
andSpooledTemporaryFile
classesboth work as context managers, so you can writewithtempfile.NamedTemporaryFile()astmp:...
.(Contributed by Alexander Belopolsky;bpo-2021.)The
test.test_support
module gained a numberof context managers useful for writing tests.EnvironmentVarGuard()
is acontext manager that temporarily changes environment variables andautomatically restores them to their old values.Another context manager,
TransientResource
, can surround callsto resources that may or may not be available; it will catch andignore a specified list of exceptions. For example,a network test may ignore certain failures when connecting to anexternal web site:withtest_support.TransientResource(IOError,errno=errno.ETIMEDOUT):f=urllib.urlopen('https://sf.net')...
Finally,
check_warnings()
resets thewarning
module'swarning filters and returns an object that will record all warningmessages triggered (bpo-3781):withtest_support.check_warnings()aswrec:warnings.simplefilter("always")# ... code that triggers a warning ...assertstr(wrec.message)=="function is outdated"assertlen(wrec.warnings)==1,"Multiple warnings raised"
(由 Brett Cannon 貢獻。)
The
textwrap
module can now preserve existing whitespaceat the beginnings and ends of the newly created linesby specifyingdrop_whitespace=False
as an argument:>>>S="""This sentence has a bunch of... extra whitespace.""">>>printtextwrap.fill(S,width=15)This sentencehas a bunchof extrawhitespace.>>>printtextwrap.fill(S,drop_whitespace=False,width=15)This sentence has a bunch of extra whitespace.>>>
(由 Dwayne Bailey 貢獻;bpo-1581073。)
The
threading
module API is being changed to use propertiessuch asdaemon
instead ofsetDaemon()
andisDaemon()
methods, and some methods have been renamed to useunderscores instead of camel-case; for example, theactiveCount()
method is renamed toactive_count()
. Boththe 2.6 and 3.0 versions of the module support the same propertiesand renamed methods, but don't remove the old methods. No date has been setfor the deprecation of the old APIs in Python 3.x; the old APIs won'tbe removed in any 2.x version.(Carried out by several people, most notably Benjamin Peterson.)The
threading
module'sThread
objectsgained anident
property that returns the thread'sidentifier, a nonzero integer. (Contributed by Gregory P. Smith;bpo-2871.)The
timeit
module now accepts callables as well as stringsfor the statement being timed and for the setup code.Two convenience functions were added for creatingTimer
instances:repeat(stmt,setup,time,repeat,number)
andtimeit(stmt,setup,time,number)
create an instance and callthe corresponding method. (Contributed by Erik Demaine;bpo-1533909.)The
Tkinter
module now accepts lists and tuples for options,separating the elements by spaces before passing the resulting value toTcl/Tk.(Contributed by Guilherme Polo;bpo-2906.)The
turtle
module for turtle graphics was greatly enhanced byGregor Lingl. New features in the module include:Better animation of turtle movement and rotation.
Control over turtle movement using the new
delay()
,tracer()
, andspeed()
methods.The ability to set new shapes for the turtle, and todefine a new coordinate system.
Turtles now have an
undo()
method that can roll back actions.Simple support for reacting to input events such as mouse and keyboardactivity, making it possible to write simple games.
A
turtle.cfg
file can be used to customize the starting appearanceof the turtle's screen.The module's docstrings can be replaced by new docstrings that have beentranslated into another language.
An optional
timeout
parameter was added to theurllib.urlopen
function and theurllib.ftpwrapper
class constructor, as well as theurllib2.urlopen
function. The parameter specifies a timeoutmeasured in seconds. For example:>>>u=urllib2.urlopen("http://slow.example.com", timeout=3)Traceback (most recent call last):...urllib2.URLError:<urlopen error timed out>>>>
(Added by Facundo Batista.)
The Unicode database provided by the
unicodedata
modulehas been updated to version 5.1.0. (Updated byMartin von Löwis;bpo-3811.)The
warnings
module'sformatwarning()
andshowwarning()
gained an optionalline argument that can be used to supply theline of source code. (Added as part ofbpo-1631171, which re-implementedpart of thewarnings
module in C code.)A new function,
catch_warnings()
, is a context managerintended for testing purposes that lets you temporarily modify thewarning filters and then restore their original values (bpo-3781).The XML-RPC
SimpleXMLRPCServer
andDocXMLRPCServer
classes can now be prevented from immediately opening and binding totheir socket by passingFalse
as thebind_and_activateconstructor parameter. This can be used to modify the instance'sallow_reuse_address
attribute before calling theserver_bind()
andserver_activate()
methods toopen the socket and begin listening for connections.(Contributed by Peter Parente;bpo-1599845.)SimpleXMLRPCServer
also has a_send_traceback_header
attribute; if true, the exception and formatted traceback are returnedas HTTP headers "X-Exception" and "X-Traceback". This feature isfor debugging purposes only and should not be used on production serversbecause the tracebacks might reveal passwords or other sensitiveinformation. (Contributed by Alan McIntyre as part of hisproject for Google's Summer of Code 2007.)The
xmlrpclib
module no longer automatically convertsdatetime.date
anddatetime.time
to thexmlrpclib.DateTime
type; the conversion semantics werenot necessarily correct for all applications. Code usingxmlrpclib
should convertdate
andtime
instances. (bpo-1330538) The code can also handledates before 1900 (contributed by Ralf Schmitt;bpo-2014)and 64-bit integers represented by using<i8>
in XML-RPC responses(contributed by Riku Lindblad;bpo-2985).The
zipfile
module'sZipFile
class now hasextract()
andextractall()
methods that will unpacka single file or all the files in the archive to the current directory, orto a specified directory:z=zipfile.ZipFile('python-251.zip')# Unpack a single file, writing it relative# to the /tmp directory.z.extract('Python/sysmodule.c','/tmp')# Unpack all the files in the archive.z.extractall()
(由 Alan McIntyre 貢獻;bpo-467924。)
The
open()
,read()
andextract()
methods can nowtake either a filename or aZipInfo
object. This is useful when anarchive accidentally contains a duplicated filename.(Contributed by Graham Horler;bpo-1775025.)Finally,
zipfile
now supports using Unicode filenamesfor archived files. (Contributed by Alexey Borzenkov;bpo-1734346.)
ast
模組¶
Theast
module provides an Abstract Syntax Treerepresentation of Python code, and Armin Ronachercontributed a set of helper functions that perform a variety ofcommon tasks. These will be useful for HTML templatingpackages, code analyzers, and similar tools that processPython code.
Theparse()
function takes an expression and returns an AST.Thedump()
function outputs a representation of a tree, suitablefor debugging:
importastt=ast.parse("""d ={}for i in 'abcdefghijklm': d[i + i] = ord(i) - ord('a') + 1print d""")printast.dump(t)
This outputs a deeply nested tree:
Module(body=[Assign(targets=[Name(id='d',ctx=Store())],value=Dict(keys=[],values=[]))For(target=Name(id='i',ctx=Store()),iter=Str(s='abcdefghijklm'),body=[Assign(targets=[Subscript(value=Name(id='d',ctx=Load()),slice=Index(value=BinOp(left=Name(id='i',ctx=Load()),op=Add(),right=Name(id='i',ctx=Load()))),ctx=Store())],value=BinOp(left=BinOp(left=Call(func=Name(id='ord',ctx=Load()),args=[Name(id='i',ctx=Load())],keywords=[],starargs=None,kwargs=None),op=Sub(),right=Call(func=Name(id='ord',ctx=Load()),args=[Str(s='a')],keywords=[],starargs=None,kwargs=None)),op=Add(),right=Num(n=1)))],orelse=[])Print(dest=None,values=[Name(id='d',ctx=Load())],nl=True)])
Theliteral_eval()
method takes a string or an ASTrepresenting a literal expression, parses and evaluates it, andreturns the resulting value. A literal expression is a Pythonexpression containing only strings, numbers, dictionaries,etc. but no statements or function calls. If you need toevaluate an expression but cannot accept the security risk of using aneval()
call,literal_eval()
will handle it safely:
>>>literal='("a", "b", {2:4, 3:8, 1:2})'>>>printast.literal_eval(literal)('a', 'b', {1: 2, 2: 4, 3: 8})>>>printast.literal_eval('"a" + "b"')Traceback (most recent call last):...ValueError:malformed string
The module also includesNodeVisitor
andNodeTransformer
classes for traversing and modifying an AST,and functions for common transformations such as changing linenumbers.
future_builtins
模組¶
Python 3.0 makes many changes to the repertoire of built-infunctions, and most of the changes can't be introduced in the Python2.x series because they would break compatibility.Thefuture_builtins
module provides versionsof these built-in functions that can be imported when writing3.0-compatible code.
The functions in this module currently include:
ascii(obj)
: equivalent torepr()
. In Python 3.0,repr()
will return a Unicode string, whileascii()
willreturn a pure ASCII bytestring.filter(predicate,iterable)
,map(func,iterable1,...)
: the 3.0 versionsreturn iterators, unlike the 2.x builtins which return lists.hex(value)
,oct(value)
: instead of calling the__hex__()
or__oct__()
methods, these versions willcall the__index__()
method and convert the result to hexadecimalor octal.oct()
will use the new0o
notation for itsresult.
Thejson
module: JavaScript Object Notation¶
The newjson
module supports the encoding and decoding of Python types inJSON (Javascript Object Notation). JSON is a lightweight interchange formatoften used in web applications. For more information about JSON, seehttp://www.json.org.
json
comes with support for decoding and encoding most built-in Pythontypes. The following example encodes and decodes a dictionary:
>>>importjson>>>data={"spam":"foo","parrot":42}>>>in_json=json.dumps(data)# Encode the data>>>in_json'{"parrot": 42, "spam": "foo"}'>>>json.loads(in_json)# Decode into a Python object{"spam": "foo", "parrot": 42}
It's also possible to write your own decoders and encoders to supportmore types. Pretty-printing of the JSON strings is also supported.
json
(originally called simplejson) was written by BobIppolito.
Theplistlib
module: A Property-List Parser¶
The.plist
format is commonly used on Mac OS X tostore basic data types (numbers, strings, lists,and dictionaries) by serializing them into an XML-based format.It resembles the XML-RPC serialization of data types.
Despite being primarily used on Mac OS X, the formathas nothing Mac-specific about it and the Python implementation workson any platform that Python supports, so theplistlib
modulehas been promoted to the standard library.
Using the module is simple:
importsysimportplistlibimportdatetime# Create data structuredata_struct=dict(lastAccessed=datetime.datetime.now(),version=1,categories=('Personal','Shared','Private'))# Create string containing XML.plist_str=plistlib.writePlistToString(data_struct)new_struct=plistlib.readPlistFromString(plist_str)printdata_structprintnew_struct# Write data structure to a file and read it back.plistlib.writePlist(data_struct,'/tmp/customizations.plist')new_struct=plistlib.readPlist('/tmp/customizations.plist')# read/writePlist accepts file-like objects as well as paths.plistlib.writePlist(data_struct,sys.stdout)
ctypes Enhancements¶
Thomas Heller continued to maintain and enhance thectypes
module.
ctypes
now supports ac_bool
datatypethat represents the C99bool
type. (Contributed by David Remahl;bpo-1649190.)
Thectypes
string, buffer and array types have improvedsupport for extended slicing syntax,where various combinations of(start,stop,step)
are supplied.(Implemented by Thomas Wouters.)
Allctypes
data types now supportfrom_buffer()
andfrom_buffer_copy()
methods that create a ctypes instance based on aprovided buffer object.from_buffer_copy()
copiesthe contents of the object,whilefrom_buffer()
will share the same memory area.
A new calling convention tellsctypes
to clear theerrno
orWin32 LastError variables at the outset of each wrapped call.(Implemented by Thomas Heller;bpo-1798.)
You can now retrieve the Unixerrno
variable after a functioncall. When creating a wrapped function, you can supplyuse_errno=True
as a keyword parameter to theDLL()
functionand then call the module-level methodsset_errno()
andget_errno()
to set and retrieve the error value.
The Win32 LastError variable is similarly supported bytheDLL()
,OleDLL()
, andWinDLL()
functions.You supplyuse_last_error=True
as a keyword parameterand then call the module-level methodsset_last_error()
andget_last_error()
.
Thebyref()
function, used to retrieve a pointer to a ctypesinstance, now has an optionaloffset parameter that is a bytecount that will be added to the returned pointer.
Improved SSL Support¶
Bill Janssen made extensive improvements to Python 2.6's support forthe Secure Sockets Layer by adding a new module,ssl
, that'sbuilt atop theOpenSSL library.This new module provides more control over the protocol negotiated,the X.509 certificates used, and has better support for writing SSLservers (as opposed to clients) in Python. The existing SSL supportin thesocket
module hasn't been removed and continues to work,though it will be removed in Python 3.0.
To use the new module, you must first create a TCP connection in theusual way and then pass it to thessl.wrap_socket()
function.It's possible to specify whether a certificate is required, and toobtain certificate info by calling thegetpeercert()
method.
也參考
The documentation for thessl
module.
Deprecations and Removals¶
String exceptions have been removed. Attempting to use them raises a
TypeError
.Changes to the
Exception
interfaceas dictated byPEP 352 continue to be made. For 2.6,themessage
attribute is being deprecated in favor of theargs
attribute.(3.0-warning mode) Python 3.0 will feature a reorganized standardlibrary that will drop many outdated modules and rename others.Python 2.6 running in 3.0-warning mode will warn about these moduleswhen they are imported.
The list of deprecated modules is:
audiodev
,bgenlocations
,buildtools
,bundlebuilder
,Canvas
,compiler
,dircache
,dl
,fpformat
,gensuitemodule
,ihooks
,imageop
,imgfile
,linuxaudiodev
,mhlib
,mimetools
,multifile
,new
,pure
,statvfs
,sunaudiodev
,test.testall
, andtoaiff
.The
gopherlib
module has been removed.The
MimeWriter
module andmimify
modulehave been deprecated; use theemail
package instead.The
md5
module has been deprecated; use thehashlib
moduleinstead.The
posixfile
module has been deprecated;fcntl.lockf()
provides better locking.The
popen2
module has been deprecated; use thesubprocess
module.The
rgbimg
module has been removed.The
sets
module has been deprecated; it's better touse the built-inset
andfrozenset
types.The
sha
module has been deprecated; use thehashlib
moduleinstead.
建置和 C API 變更¶
Python 建置程序和 C API 的變更包括:
Python now must be compiled with C89 compilers (after 19years!). This means that the Python source tree has dropped itsown implementations of
memmove()
andstrerror()
, whichare in the C89 standard library.Python 2.6 can be built with Microsoft Visual Studio 2008 (version9.0), and this is the new default compiler. See the
PCbuild
directory for the build files. (Implemented byChristian Heimes.)On Mac OS X, Python 2.6 can be compiled as a 4-way universal build.Theconfigure scriptcan take a
--with-universal-archs=[32-bit|64-bit|all]
switch, controlling whether the binaries are built for 32-bitarchitectures (x86, PowerPC), 64-bit (x86-64 and PPC-64), or both.(Contributed by Ronald Oussoren.)A new function added in Python 2.6.6,
PySys_SetArgvEx()
, setsthe value ofsys.argv
and can optionally updatesys.path
toinclude the directory containing the script named bysys.argv[0]
depending on the value of anupdatepath parameter.This function was added to close a security hole for applicationsthat embed Python. The old function,
PySys_SetArgv()
, wouldalways updatesys.path
, and sometimes it would add the currentdirectory. This meant that, if you ran an application embeddingPython in a directory controlled by someone else, attackers couldput a Trojan-horse module in the directory (say, a file namedos.py
) that your application would then import and run.If you maintain a C/C++ application that embeds Python, checkwhether you're calling
PySys_SetArgv()
and carefully considerwhether the application should be usingPySys_SetArgvEx()
withupdatepath set to false. Note that using this function willbreak compatibility with Python versions 2.6.5 and earlier; if youhave to continue working with earlier versions, you can leavethe call toPySys_SetArgv()
alone and callPyRun_SimpleString("sys.path.pop(0)\n")
afterwards to discardthe firstsys.path
component.Security issue reported asCVE 2008-5983;discussed ingh-50003, and fixed by Antoine Pitrou.
The BerkeleyDB module now has a C API object, available as
bsddb.db.api
. This object can be used by other C extensionsthat wish to use thebsddb
module for their own purposes.(Contributed by Duncan Grisby.)The new buffer interface, previously described inthe PEP 3118 section,adds
PyObject_GetBuffer()
andPyBuffer_Release()
,as well as a few other functions.Python's use of the C stdio library is now thread-safe, or at leastas thread-safe as the underlying library is. A long-standing potentialbug occurred if one thread closed a file object while another threadwas reading from or writing to the object. In 2.6 file objectshave a reference count, manipulated by the
PyFile_IncUseCount()
andPyFile_DecUseCount()
functions. File objects can't be closed unless the reference countis zero.PyFile_IncUseCount()
should be called while the GILis still held, before carrying out an I/O operation using theFILE*
pointer, andPyFile_DecUseCount()
should be calledimmediately after the GIL is re-acquired.(Contributed by Antoine Pitrou and Gregory P. Smith.)Importing modules simultaneously in two different threads no longerdeadlocks; it will now raise an
ImportError
. A new APIfunction,PyImport_ImportModuleNoBlock()
, will look for amodule insys.modules
first, then try to import it afteracquiring an import lock. If the import lock is held by anotherthread, anImportError
is raised.(Contributed by Christian Heimes.)Several functions return information about the platform'sfloating-point support.
PyFloat_GetMax()
returnsthe maximum representable floating-point value,andPyFloat_GetMin()
returns the minimumpositive value.PyFloat_GetInfo()
returns an objectcontaining more information from thefloat.h
file, such as"mant_dig"
(number of digits in the mantissa),"epsilon"
(smallest difference between 1.0 and the next largest valuerepresentable), and several others.(Contributed by Christian Heimes;bpo-1534.)C functions and methods that use
PyComplex_AsCComplex()
will now accept arguments thathave a__complex__()
method. In particular, the functions in thecmath
module will now accept objects with this method.This is a backport of a Python 3.0 change.(Contributed by Mark Dickinson;bpo-1675423.)Python's C API now includes two functions for case-insensitive stringcomparisons,
PyOS_stricmp(char*,char*)
andPyOS_strnicmp(char*,char*,Py_ssize_t)
.(Contributed by Christian Heimes;bpo-1635.)Many C extensions define their own little macro for addingintegers and strings to the module's dictionary in the
init*
function. Python 2.6 finally defines standard macrosfor adding values to a module,PyModule_AddStringMacro
andPyModule_AddIntMacro()
. (Contributed byChristian Heimes.)Some macros were renamed in both 3.0 and 2.6 to make it clearer thatthey are macros,not functions.
Py_Size()
becamePy_SIZE()
,Py_Type()
becamePy_TYPE()
, andPy_Refcnt()
becamePy_REFCNT()
.The mixed-case macros are still availablein Python 2.6 for backward compatibility.(bpo-1629)Distutils now places C extensions it builds in adifferent directory when running on a debug version of Python.(Contributed by Collin Winter;bpo-1530959.)
Several basic data types, such as integers and strings, maintaininternal free lists of objects that can be re-used. The datastructures for these free lists now follow a naming convention: thevariable is always named
free_list
, the counter is always namednumfree
, and a macroPy<typename>_MAXFREELIST
isalways defined.A new Makefile target, "make patchcheck", prepares the Python source treefor making a patch: it fixes trailing whitespace in all modified
.py
files, checks whether the documentation has been changed,and reports whether theMisc/ACKS
andMisc/NEWS
fileshave been updated.(Contributed by Brett Cannon.)Another new target, "make profile-opt", compiles a Python binaryusing GCC's profile-guided optimization. It compiles Python withprofiling enabled, runs the test suite to obtain a set of profilingresults, and then compiles using these results for optimization.(Contributed by Gregory P. Smith.)
Port-Specific Changes: Windows¶
The support for Windows 95, 98, ME and NT4 has been dropped.Python 2.6 requires at least Windows 2000 SP4.
The new default compiler on Windows is Visual Studio 2008 (version9.0). The build directories for Visual Studio 2003 (version 7.1) and2005 (version 8.0) were moved into the PC/ directory. The new
PCbuild
directory supports cross compilation for X64, debugbuilds and Profile Guided Optimization (PGO). PGO builds are roughly10% faster than normal builds. (Contributed by Christian Heimeswith help from Amaury Forgeot d'Arc and Martin von Löwis.)The
msvcrt
module now supportsboth the normal and wide char variants of the console I/OAPI. Thegetwch()
function reads a keypress and returns a Unicodevalue, as does thegetwche()
function. Theputwch()
functiontakes a Unicode character and writes it to the console.(Contributed by Christian Heimes.)os.path.expandvars()
will now expand environment variables inthe form "%var%", and "~user" will be expanded into the user's homedirectory path. (Contributed by Josiah Carlson;bpo-957650.)The
socket
module's socket objects now have anioctl()
method that provides a limited interface to theWSAIoctl()
system interface.The
_winreg
module now has a function,ExpandEnvironmentStrings()
,that expands environment variable references such as%NAME%
in an input string. The handle objects provided by thismodule now support the context protocol, so they can be usedinwith
statements. (Contributed by Christian Heimes.)_winreg
also has better support for x64 systems,exposing theDisableReflectionKey()
,EnableReflectionKey()
,andQueryReflectionKey()
functions, which enable and disableregistry reflection for 32-bit processes running on 64-bit systems.(bpo-1753245)The
msilib
module'sRecord
objectgainedGetInteger()
andGetString()
methods thatreturn field values as an integer or a string.(Contributed by Floris Bruynooghe;bpo-2125.)
Port-Specific Changes: Mac OS X¶
When compiling a framework build of Python, you can now specify theframework name to be used by providing the
--with-framework-name=
option to theconfigure script.The
macfs
module has been removed. This in turn required themacostools.touched()
function to be removed because it depended on themacfs
module. (bpo-1490190)Many other Mac OS modules have been deprecated and will be removed inPython 3.0:
_builtinSuites
,aepack
,aetools
,aetypes
,applesingle
,appletrawmain
,appletrunner
,argvemulator
,Audio_mac
,autoGIL
,Carbon
,cfmfile
,CodeWarrior
,ColorPicker
,EasyDialogs
,Explorer
,Finder
,FrameWork
,findertools
,ic
,icglue
,icopen
,macerrors
,MacOS
,macfs
,macostools
,macresource
,MiniAEFrame
,Nav
,Netscape
,OSATerminology
,pimp
,PixMapWrapper
,StdSuites
,SystemEvents
,Terminal
, andterminalcommand
.
Port-Specific Changes: IRIX¶
A number of old IRIX-specific modules were deprecated and willbe removed in Python 3.0:al
andAL
,cd
,cddb
,cdplayer
,CL
andcl
,DEVICE
,ERRNO
,FILE
,FL
andfl
,flp
,fm
,GET
,GLWS
,GL
andgl
,IN
,IOCTL
,jpeg
,panelparser
,readcd
,SV
andsv
,torgb
,videoreader
, andWAIT
.
Porting to Python 2.6¶
This section lists previously described changes and other bugfixesthat may require changes to your code:
Classes that aren't supposed to be hashable shouldset
__hash__=None
in their definitions to indicatethe fact.String exceptions have been removed. Attempting to use them raises a
TypeError
.The
__init__()
method ofcollections.deque
now clears any existing contents of the dequebefore adding elements from the iterable. This change makes thebehavior matchlist.__init__()
.object.__init__()
previously accepted arbitrary arguments andkeyword arguments, ignoring them. In Python 2.6, this is no longerallowed and will result in aTypeError
. This will affect__init__()
methods that end up calling the correspondingmethod onobject
(perhaps through usingsuper()
).Seebpo-1683368 for discussion.The
Decimal
constructor now accepts leading and trailingwhitespace when passed a string. Previously it would raise anInvalidOperation
exception. On the other hand, thecreate_decimal()
method ofContext
objects nowexplicitly disallows extra whitespace, raising aConversionSyntax
exception.Due to an implementation accident, if you passed a file path tothe built-in
__import__()
function, it would actually importthe specified file. This was never intended to work, however, andthe implementation now explicitly checks for this case and raisesanImportError
.C API: the
PyImport_Import()
andPyImport_ImportModule()
functions now default to absolute imports, not relative imports.This will affect C extensions that import other modules.C API: extension data types that shouldn't be hashableshould define their
tp_hash
slot toPyObject_HashNotImplemented()
.The
socket
module exceptionsocket.error
now inheritsfromIOError
. Previously it wasn't a subclass ofStandardError
but now it is, throughIOError
.(Implemented by Gregory P. Smith;bpo-1706815.)The
xmlrpclib
module no longer automatically convertsdatetime.date
anddatetime.time
to thexmlrpclib.DateTime
type; the conversion semantics werenot necessarily correct for all applications. Code usingxmlrpclib
should convertdate
andtime
instances. (bpo-1330538)(3.0-warning mode) The
Exception
class now warnswhen accessed using slicing or index access; havingException
behave like a tuple is being phased out.(3.0-warning mode) inequality comparisons between two dictionariesor two objects that don't implement comparison methods are reportedas warnings.
dict1==dict2
still works, butdict1<dict2
is being phased out.Comparisons between cells, which are an implementation detail of Python'sscoping rules, also cause warnings because such comparisons are forbiddenentirely in 3.0.
For applications that embed Python:
The
PySys_SetArgvEx()
function was added in Python 2.6.6,letting applications close a security hole when the existingPySys_SetArgv()
function was used. Check whether you'recallingPySys_SetArgv()
and carefully consider whether theapplication should be usingPySys_SetArgvEx()
withupdatepath set to false.
致謝¶
The author would like to thank the following people for offeringsuggestions, corrections and assistance with various drafts of thisarticle: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy,Jim Jewett, Kent Johnson, Chris Lambacher, Martin Michlmayr,Antoine Pitrou, Brian Warner.