### 导航
- [索引](../genindex.xhtml "总目录")
- [模块](../py-modindex.xhtml "Python 模块索引") |
- [下一页](2.2.xhtml "What's New in Python 2.2") |
- [上一页](2.4.xhtml "What's New in Python 2.4") |
- ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png)
- [Python](https://www.python.org/) »
- zh\_CN 3.7.3 [文档](../index.xhtml) »
- [Python 有什么新变化?](index.xhtml) »
- $('.inline-search').show(0); |
# What's New in Python 2.3
作者A.M. Kuchling
This article explains the new features in Python 2.3. Python 2.3 was released on July 29, 2003.
The main themes for Python 2.3 are polishing some of the features added in 2.2, adding various small but useful enhancements to the core language, and expanding the standard library. The new object model introduced in the previous version has benefited from 18 months of bugfixes and from optimization efforts that have improved the performance of new-style classes. A few new built-in functions have been added such as [`sum()`](../library/functions.xhtml#sum "sum") and [`enumerate()`](../library/functions.xhtml#enumerate "enumerate"). The [`in`](../reference/expressions.xhtml#in)operator can now be used for substring searches (e.g. `"ab" in "abc"` returns [`True`](../library/constants.xhtml#True "True")).
Some of the many new library features include Boolean, set, heap, and date/time data types, the ability to import modules from ZIP-format archives, metadata support for the long-awaited Python catalog, an updated version of IDLE, and modules for logging messages, wrapping text, parsing CSV files, processing command-line options, using BerkeleyDB databases... the list of new and enhanced modules is lengthy.
This article doesn't attempt to provide a complete specification of the new features, but instead provides a convenient overview. For full details, you should refer to the documentation for Python 2.3, such as the Python Library Reference and the Python Reference Manual. If you want to understand the complete implementation and design rationale, refer to the PEP for a particular new feature.
## PEP 218: A Standard Set Datatype
The new `sets` module contains an implementation of a set datatype. The `Set` class is for mutable sets, sets that can have members added and removed. The `ImmutableSet` class is for sets that can't be modified, and instances of `ImmutableSet` can therefore be used as dictionary keys. Sets are built on top of dictionaries, so the elements within a set must be hashable.
Here's a simple example:
```
>>> import sets
>>> S = sets.Set([1,2,3])
>>> S
Set([1, 2, 3])
>>> 1 in S
True
>>> 0 in S
False
>>> S.add(5)
>>> S.remove(3)
>>> S
Set([1, 2, 5])
>>>
```
The union and intersection of sets can be computed with the `union()` and `intersection()` methods; an alternative notation uses the bitwise operators `&` and `|`. Mutable sets also have in-place versions of these methods, `union_update()` and `intersection_update()`.
```
>>> S1 = sets.Set([1,2,3])
>>> S2 = sets.Set([4,5,6])
>>> S1.union(S2)
Set([1, 2, 3, 4, 5, 6])
>>> S1 | S2 # Alternative notation
Set([1, 2, 3, 4, 5, 6])
>>> S1.intersection(S2)
Set([])
>>> S1 & S2 # Alternative notation
Set([])
>>> S1.union_update(S2)
>>> S1
Set([1, 2, 3, 4, 5, 6])
>>>
```
It's also possible to take the symmetric difference of two sets. This is the set of all elements in the union that aren't in the intersection. Another way of putting it is that the symmetric difference contains all elements that are in exactly one set. Again, there's an alternative notation (`^`), and an in-place version with the ungainly name `symmetric_difference_update()`.
```
>>> S1 = sets.Set([1,2,3,4])
>>> S2 = sets.Set([3,4,5,6])
>>> S1.symmetric_difference(S2)
Set([1, 2, 5, 6])
>>> S1 ^ S2
Set([1, 2, 5, 6])
>>>
```
There are also `issubset()` and `issuperset()` methods for checking whether one set is a subset or superset of another:
```
>>> S1 = sets.Set([1,2,3])
>>> S2 = sets.Set([2,3])
>>> S2.issubset(S1)
True
>>> S1.issubset(S2)
False
>>> S1.issuperset(S2)
True
>>>
```
参见
[**PEP 218**](https://www.python.org/dev/peps/pep-0218) \[https://www.python.org/dev/peps/pep-0218\] - Adding a Built-In Set Object TypePEP written by Greg V. Wilson. Implemented by Greg V. Wilson, Alex Martelli, and GvR.
## PEP 255: Simple Generators
In Python 2.2, generators were added as an optional feature, to be enabled by a `from __future__ import generators` directive. In 2.3 generators no longer need to be specially enabled, and are now always present; this means that [`yield`](../reference/simple_stmts.xhtml#yield) is now always a keyword. The rest of this section is a copy of the description of generators from the "What's New in Python 2.2" document; if you read it back when Python 2.2 came out, you can skip the rest of this section.
You're doubtless familiar with how function calls work in Python or C. When you call a function, it gets a private namespace where its local variables are created. When the function reaches a [`return`](../reference/simple_stmts.xhtml#return) statement, the local variables are destroyed and the resulting value is returned to the caller. A later call to the same function will get a fresh new set of local variables. But, what if the local variables weren't thrown away on exiting a function? What if you could later resume the function where it left off? This is what generators provide; they can be thought of as resumable functions.
Here's the simplest example of a generator function:
```
def generate_ints(N):
for i in range(N):
yield i
```
A new keyword, [`yield`](../reference/simple_stmts.xhtml#yield), was introduced for generators. Any function containing a `yield` statement is a generator function; this is detected by Python's bytecode compiler which compiles the function specially as a result.
When you call a generator function, it doesn't return a single value; instead it returns a generator object that supports the iterator protocol. On executing the [`yield`](../reference/simple_stmts.xhtml#yield) statement, the generator outputs the value of `i`, similar to a [`return`](../reference/simple_stmts.xhtml#return) statement. The big difference between `yield` and a `return` statement is that on reaching a `yield` the generator's state of execution is suspended and local variables are preserved. On the next call to the generator's `.next()`method, the function will resume executing immediately after the `yield` statement. (For complicated reasons, the `yield`statement isn't allowed inside the [`try`](../reference/compound_stmts.xhtml#try) block of a `try`...`finally` statement; read [**PEP 255**](https://www.python.org/dev/peps/pep-0255) \[https://www.python.org/dev/peps/pep-0255\] for a full explanation of the interaction between `yield` and exceptions.)
Here's a sample usage of the `generate_ints()` generator:
```
>>> gen = generate_ints(3)
>>> gen
<generator object at 0x8117f90>
>>> gen.next()
0
>>> gen.next()
1
>>> gen.next()
2
>>> gen.next()
Traceback (most recent call last):
File "stdin", line 1, in ?
File "stdin", line 2, in generate_ints
StopIteration
```
You could equally write `for i in generate_ints(5)`, or
```
a,b,c =
generate_ints(3)
```
.
Inside a generator function, the [`return`](../reference/simple_stmts.xhtml#return) statement can only be used without a value, and signals the end of the procession of values; afterwards the generator cannot return any further values. `return` with a value, such as `return 5`, is a syntax error inside a generator function. The end of the generator's results can also be indicated by raising [`StopIteration`](../library/exceptions.xhtml#StopIteration "StopIteration")manually, or by just letting the flow of execution fall off the bottom of the function.
You could achieve the effect of generators manually by writing your own class and storing all the local variables of the generator as instance variables. For example, returning a list of integers could be done by setting `self.count` to 0, and having the [`next()`](../library/functions.xhtml#next "next") method increment `self.count` and return it. However, for a moderately complicated generator, writing a corresponding class would be much messier. `Lib/test/test_generators.py` contains a number of more interesting examples. The simplest one implements an in-order traversal of a tree using generators recursively.
```
# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
if t:
for x in inorder(t.left):
yield x
yield t.label
for x in inorder(t.right):
yield x
```
Two other examples in `Lib/test/test_generators.py` produce solutions for the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no queen threatens another) and the Knight's Tour (a route that takes a knight to every square of an $NxN$ chessboard without visiting any square twice).
The idea of generators comes from other programming languages, especially Icon (<https://www.cs.arizona.edu/icon/>), where the idea of generators is central. In Icon, every expression and function call behaves like a generator. One example from "An Overview of the Icon Programming Language" at <https://www.cs.arizona.edu/icon/docs/ipd266.htm> gives an idea of what this looks like:
```
sentence := "Store it in the neighboring harbor"
if (i := find("or", sentence)) > 5 then write(i)
```
In Icon the `find()` function returns the indexes at which the substring "or" is found: 3, 23, 33. In the [`if`](../reference/compound_stmts.xhtml#if) statement, `i` is first assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon retries it with the second value of 23. 23 is greater than 5, so the comparison now succeeds, and the code prints the value 23 to the screen.
Python doesn't go nearly as far as Icon in adopting generators as a central concept. Generators are considered part of the core Python language, but learning or using them isn't compulsory; if they don't solve any problems that you have, feel free to ignore them. One novel feature of Python's interface as compared to Icon's is that a generator's state is represented as a concrete object (the iterator) that can be passed around to other functions or stored in a data structure.
参见
[**PEP 255**](https://www.python.org/dev/peps/pep-0255) \[https://www.python.org/dev/peps/pep-0255\] - 简单生成器Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland. Implemented mostly by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.
## PEP 263: Source Code Encodings
Python source files can now be declared as being in different character set encodings. Encodings are declared by including a specially formatted comment in the first or second line of the source file. For example, a UTF-8 file can be declared with:
```
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
```
Without such an encoding declaration, the default encoding used is 7-bit ASCII. Executing or importing modules that contain string literals with 8-bit characters and have no encoding declaration will result in a [`DeprecationWarning`](../library/exceptions.xhtml#DeprecationWarning "DeprecationWarning") being signalled by Python 2.3; in 2.4 this will be a syntax error.
The encoding declaration only affects Unicode string literals, which will be converted to Unicode using the specified encoding. Note that Python identifiers are still restricted to ASCII characters, so you can't have variable names that use characters outside of the usual alphanumerics.
参见
[**PEP 263**](https://www.python.org/dev/peps/pep-0263) \[https://www.python.org/dev/peps/pep-0263\] - Defining Python Source Code EncodingsWritten by Marc-André Lemburg and Martin von Löwis; implemented by Suzuki Hisao and Martin von Löwis.
## PEP 273: Importing Modules from ZIP Archives
The new [`zipimport`](../library/zipimport.xhtml#module-zipimport "zipimport: support for importing Python modules from ZIP archives.") module adds support for importing modules from a ZIP-format archive. You don't need to import the module explicitly; it will be automatically imported if a ZIP archive's filename is added to `sys.path`. For example:
```
amk@nyman:~/src/python$ unzip -l /tmp/example.zip
Archive: /tmp/example.zip
Length Date Time Name
-------- ---- ---- ----
8467 11-26-02 22:30 jwzthreading.py
-------- -------
8467 1 file
amk@nyman:~/src/python$ ./python
Python 2.3 (#1, Aug 1 2003, 19:54:32)
>>> import sys
>>> sys.path.insert(0, '/tmp/example.zip') # Add .zip file to front of path
>>> import jwzthreading
>>> jwzthreading.__file__
'/tmp/example.zip/jwzthreading.py'
>>>
```
An entry in `sys.path` can now be the filename of a ZIP archive. The ZIP archive can contain any kind of files, but only files named `*.py`, `*.pyc`, or `*.pyo` can be imported. If an archive only contains `*.py` files, Python will not attempt to modify the archive by adding the corresponding `*.pyc` file, meaning that if a ZIP archive doesn't contain `*.pyc` files, importing may be rather slow.
A path within the archive can also be specified to only import from a subdirectory; for example, the path `/tmp/example.zip/lib/` would only import from the `lib/` subdirectory within the archive.
参见
[**PEP 273**](https://www.python.org/dev/peps/pep-0273) \[https://www.python.org/dev/peps/pep-0273\] - Import Modules from Zip ArchivesWritten by James C. Ahlstrom, who also provided an implementation. Python 2.3 follows the specification in [**PEP 273**](https://www.python.org/dev/peps/pep-0273) \[https://www.python.org/dev/peps/pep-0273\], but uses an implementation written by Just van Rossum that uses the import hooks described in [**PEP 302**](https://www.python.org/dev/peps/pep-0302) \[https://www.python.org/dev/peps/pep-0302\]. See section [PEP 302: New Import Hooks](#section-pep302) for a description of the new import hooks.
## PEP 277: Unicode file name support for Windows NT
On Windows NT, 2000, and XP, the system stores file names as Unicode strings. Traditionally, Python has represented file names as byte strings, which is inadequate because it renders some file names inaccessible.
Python now allows using arbitrary Unicode strings (within the limitations of the file system) for all functions that expect file names, most notably the [`open()`](../library/functions.xhtml#open "open") built-in function. If a Unicode string is passed to [`os.listdir()`](../library/os.xhtml#os.listdir "os.listdir"), Python now returns a list of Unicode strings. A new function, `os.getcwdu()`, returns the current directory as a Unicode string.
Byte strings still work as file names, and on Windows Python will transparently convert them to Unicode using the `mbcs` encoding.
Other systems also allow Unicode strings as file names but convert them to byte strings before passing them to the system, which can cause a [`UnicodeError`](../library/exceptions.xhtml#UnicodeError "UnicodeError")to be raised. Applications can test whether arbitrary Unicode strings are supported as file names by checking [`os.path.supports_unicode_filenames`](../library/os.path.xhtml#os.path.supports_unicode_filenames "os.path.supports_unicode_filenames"), a Boolean value.
Under MacOS, [`os.listdir()`](../library/os.xhtml#os.listdir "os.listdir") may now return Unicode filenames.
参见
[**PEP 277**](https://www.python.org/dev/peps/pep-0277) \[https://www.python.org/dev/peps/pep-0277\] - Unicode file name support for Windows NTWritten by Neil Hodgson; implemented by Neil Hodgson, Martin von Löwis, and Mark Hammond.
## PEP 278: Universal Newline Support
The three major operating systems used today are Microsoft Windows, Apple's Macintosh OS, and the various Unix derivatives. A minor irritation of cross-platform work is that these three platforms all use different characters to mark the ends of lines in text files. Unix uses the linefeed (ASCII character 10), MacOS uses the carriage return (ASCII character 13), and Windows uses a two-character sequence of a carriage return plus a newline.
Python's file objects can now support end of line conventions other than the one followed by the platform on which Python is running. Opening a file with the mode `'U'` or `'rU'` will open a file for reading in [universal newlines](../glossary.xhtml#term-universal-newlines) mode. All three line ending conventions will be translated to a `'\n'` in the strings returned by the various file methods such as `read()` and [`readline()`](../library/readline.xhtml#module-readline "readline: GNU readline support for Python. (Unix)").
Universal newline support is also used when importing modules and when executing a file with the `execfile()` function. This means that Python modules can be shared between all three operating systems without needing to convert the line-endings.
This feature can be disabled when compiling Python by specifying the `--without-universal-newlines` switch when running Python's **configure** script.
参见
[**PEP 278**](https://www.python.org/dev/peps/pep-0278) \[https://www.python.org/dev/peps/pep-0278\] - Universal Newline SupportWritten and implemented by Jack Jansen.
## PEP 279: enumerate()
A new built-in function, [`enumerate()`](../library/functions.xhtml#enumerate "enumerate"), will make certain loops a bit clearer. `enumerate(thing)`, where *thing* is either an iterator or a sequence, returns an iterator that will return `(0, thing[0])`,
```
(1,
thing[1])
```
, `(2, thing[2])`, and so forth.
A common idiom to change every element of a list looks like this:
```
for i in range(len(L)):
item = L[i]
# ... compute some result based on item ...
L[i] = result
```
This can be rewritten using [`enumerate()`](../library/functions.xhtml#enumerate "enumerate") as:
```
for i, item in enumerate(L):
# ... compute some result based on item ...
L[i] = result
```
参见
[**PEP 279**](https://www.python.org/dev/peps/pep-0279) \[https://www.python.org/dev/peps/pep-0279\] - The enumerate() built-in functionWritten and implemented by Raymond D. Hettinger.
## PEP 282: The logging Package
A standard package for writing logs, [`logging`](../library/logging.xhtml#module-logging "logging: Flexible event logging system for applications."), has been added to Python 2.3. It provides a powerful and flexible mechanism for generating logging output which can then be filtered and processed in various ways. A configuration file written in a standard format can be used to control the logging behavior of a program. Python includes handlers that will write log records to standard error or to a file or socket, send them to the system log, or even e-mail them to a particular address; of course, it's also possible to write your own handler classes.
The `Logger` class is the primary class. Most application code will deal with one or more `Logger` objects, each one used by a particular subsystem of the application. Each `Logger` is identified by a name, and names are organized into a hierarchy using `.` as the component separator. For example, you might have `Logger` instances named `server`, `server.auth` and `server.network`. The latter two instances are below `server` in the hierarchy. This means that if you turn up the verbosity for `server` or direct `server` messages to a different handler, the changes will also apply to records logged to `server.auth` and `server.network`. There's also a root `Logger` that's the parent of all other loggers.
For simple uses, the [`logging`](../library/logging.xhtml#module-logging "logging: Flexible event logging system for applications.") package contains some convenience functions that always use the root log:
```
import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')
```
This produces the following output:
```
WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
```
In the default configuration, informational and debugging messages are suppressed and the output is sent to standard error. You can enable the display of informational and debugging messages by calling the `setLevel()` method on the root logger.
Notice the `warning()` call's use of string formatting operators; all of the functions for logging messages take the arguments `(msg, arg1, arg2, ...)` and log the string resulting from `msg % (arg1, arg2, ...)`.
There's also an `exception()` function that records the most recent traceback. Any of the other functions will also record the traceback if you specify a true value for the keyword argument *exc\_info*.
```
def f():
try: 1/0
except: logging.exception('Problem recorded')
f()
```
This produces the following output:
```
ERROR:root:Problem recorded
Traceback (most recent call last):
File "t.py", line 6, in f
1/0
ZeroDivisionError: integer division or modulo by zero
```
Slightly more advanced programs will use a logger other than the root logger. The `getLogger(name)` function is used to get a particular log, creating it if it doesn't exist yet. `getLogger(None)` returns the root logger.
```
log = logging.getLogger('server')
...
log.info('Listening on port %i', port)
...
log.critical('Disk full')
...
```
Log records are usually propagated up the hierarchy, so a message logged to `server.auth` is also seen by `server` and `root`, but a `Logger`can prevent this by setting its `propagate` attribute to [`False`](../library/constants.xhtml#False "False").
There are more classes provided by the [`logging`](../library/logging.xhtml#module-logging "logging: Flexible event logging system for applications.") package that can be customized. When a `Logger` instance is told to log a message, it creates a `LogRecord` instance that is sent to any number of different `Handler` instances. Loggers and handlers can also have an attached list of filters, and each filter can cause the `LogRecord` to be ignored or can modify the record before passing it along. When they're finally output, `LogRecord` instances are converted to text by a `Formatter`class. All of these classes can be replaced by your own specially-written classes.
With all of these features the [`logging`](../library/logging.xhtml#module-logging "logging: Flexible event logging system for applications.") package should provide enough flexibility for even the most complicated applications. This is only an incomplete overview of its features, so please see the package's reference documentation for all of the details. Reading [**PEP 282**](https://www.python.org/dev/peps/pep-0282) \[https://www.python.org/dev/peps/pep-0282\] will also be helpful.
参见
[**PEP 282**](https://www.python.org/dev/peps/pep-0282) \[https://www.python.org/dev/peps/pep-0282\] - A Logging SystemWritten by Vinay Sajip and Trent Mick; implemented by Vinay Sajip.
## PEP 285: A Boolean Type
A Boolean type was added to Python 2.3. Two new constants were added to the `__builtin__` module, [`True`](../library/constants.xhtml#True "True") and [`False`](../library/constants.xhtml#False "False"). ([`True`](../library/constants.xhtml#True "True") and [`False`](../library/constants.xhtml#False "False") constants were added to the built-ins in Python 2.2.1, but the 2.2.1 versions are simply set to integer values of 1 and 0 and aren't a different type.)
The type object for this new type is named [`bool`](../library/functions.xhtml#bool "bool"); the constructor for it takes any Python value and converts it to [`True`](../library/constants.xhtml#True "True") or [`False`](../library/constants.xhtml#False "False").
```
>>> bool(1)
True
>>> bool(0)
False
>>> bool([])
False
>>> bool( (1,) )
True
```
Most of the standard library modules and built-in functions have been changed to return Booleans.
```
>>> obj = []
>>> hasattr(obj, 'append')
True
>>> isinstance(obj, list)
True
>>> isinstance(obj, tuple)
False
```
Python's Booleans were added with the primary goal of making code clearer. For example, if you're reading a function and encounter the statement `return 1`, you might wonder whether the `1` represents a Boolean truth value, an index, or a coefficient that multiplies some other quantity. If the statement is `return True`, however, the meaning of the return value is quite clear.
Python's Booleans were *not* added for the sake of strict type-checking. A very strict language such as Pascal would also prevent you performing arithmetic with Booleans, and would require that the expression in an [`if`](../reference/compound_stmts.xhtml#if) statement always evaluate to a Boolean result. Python is not this strict and never will be, as [**PEP 285**](https://www.python.org/dev/peps/pep-0285) \[https://www.python.org/dev/peps/pep-0285\] explicitly says. This means you can still use any expression in an `if` statement, even ones that evaluate to a list or tuple or some random object. The Boolean type is a subclass of the [`int`](../library/functions.xhtml#int "int") class so that arithmetic using a Boolean still works.
```
>>> True + 1
2
>>> False + 1
1
>>> False * 75
0
>>> True * 75
75
```
To sum up [`True`](../library/constants.xhtml#True "True") and [`False`](../library/constants.xhtml#False "False") in a sentence: they're alternative ways to spell the integer values 1 and 0, with the single difference that [`str()`](../library/stdtypes.xhtml#str "str") and [`repr()`](../library/functions.xhtml#repr "repr") return the strings `'True'` and `'False'`instead of `'1'` and `'0'`.
参见
[**PEP 285**](https://www.python.org/dev/peps/pep-0285) \[https://www.python.org/dev/peps/pep-0285\] - Adding a bool typeWritten and implemented by GvR.
## PEP 293: Codec Error Handling Callbacks
When encoding a Unicode string into a byte string, unencodable characters may be encountered. So far, Python has allowed specifying the error processing as either "strict" (raising [`UnicodeError`](../library/exceptions.xhtml#UnicodeError "UnicodeError")), "ignore" (skipping the character), or "replace" (using a question mark in the output string), with "strict" being the default behavior. It may be desirable to specify alternative processing of such errors, such as inserting an XML character reference or HTML entity reference into the converted string.
Python now has a flexible framework to add different processing strategies. New error handlers can be added with [`codecs.register_error()`](../library/codecs.xhtml#codecs.register_error "codecs.register_error"), and codecs then can access the error handler with [`codecs.lookup_error()`](../library/codecs.xhtml#codecs.lookup_error "codecs.lookup_error"). An equivalent C API has been added for codecs written in C. The error handler gets the necessary state information such as the string being converted, the position in the string where the error was detected, and the target encoding. The handler can then either raise an exception or return a replacement string.
Two additional error handlers have been implemented using this framework: "backslashreplace" uses Python backslash quoting to represent unencodable characters and "xmlcharrefreplace" emits XML character references.
参见
[**PEP 293**](https://www.python.org/dev/peps/pep-0293) \[https://www.python.org/dev/peps/pep-0293\] - Codec Error Handling CallbacksWritten and implemented by Walter Dörwald.
## PEP 301: Package Index and Metadata for Distutils
Support for the long-requested Python catalog makes its first appearance in 2.3.
The heart of the catalog is the new Distutils **register** command. Running `python setup.py register` will collect the metadata describing a package, such as its name, version, maintainer, description, &c., and send it to a central catalog server. The resulting catalog is available from <https://pypi.org>.
To make the catalog a bit more useful, a new optional *classifiers* keyword argument has been added to the Distutils `setup()` function. A list of [Trove](http://catb.org/~esr/trove/) \[http://catb.org/~esr/trove/\]-style strings can be supplied to help classify the software.
Here's an example `setup.py` with classifiers, written to be compatible with older versions of the Distutils:
```
from distutils import core
kw = {'name': "Quixote",
'version': "0.5.1",
'description': "A highly Pythonic Web application framework",
# ...
}
if (hasattr(core, 'setup_keywords') and
'classifiers' in core.setup_keywords):
kw['classifiers'] = \
['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Environment :: No Input/Output (Daemon)',
'Intended Audience :: Developers'],
core.setup(**kw)
```
The full list of classifiers can be obtained by running
```
python setup.py
register --list-classifiers
```
.
参见
[**PEP 301**](https://www.python.org/dev/peps/pep-0301) \[https://www.python.org/dev/peps/pep-0301\] - Package Index and Metadata for DistutilsWritten and implemented by Richard Jones.
## PEP 302: New Import Hooks
While it's been possible to write custom import hooks ever since the `ihooks` module was introduced in Python 1.3, no one has ever been really happy with it because writing new import hooks is difficult and messy. There have been various proposed alternatives such as the `imputil` and `iu`modules, but none of them has ever gained much acceptance, and none of them were easily usable from C code.
[**PEP 302**](https://www.python.org/dev/peps/pep-0302) \[https://www.python.org/dev/peps/pep-0302\] borrows ideas from its predecessors, especially from Gordon McMillan's `iu` module. Three new items are added to the [`sys`](../library/sys.xhtml#module-sys "sys: Access system-specific parameters and functions.")module:
- `sys.path_hooks` is a list of callable objects; most often they'll be classes. Each callable takes a string containing a path and either returns an importer object that will handle imports from this path or raises an [`ImportError`](../library/exceptions.xhtml#ImportError "ImportError") exception if it can't handle this path.
- `sys.path_importer_cache` caches importer objects for each path, so `sys.path_hooks` will only need to be traversed once for each path.
- `sys.meta_path` is a list of importer objects that will be traversed before `sys.path` is checked. This list is initially empty, but user code can add objects to it. Additional built-in and frozen modules can be imported by an object added to this list.
Importer objects must have a single method,
```
find_module(fullname,
path=None)
```
. *fullname* will be a module or package name, e.g. `string` or `distutils.core`. `find_module()` must return a loader object that has a single method, `load_module(fullname)`, that creates and returns the corresponding module object.
Pseudo-code for Python's new import logic, therefore, looks something like this (simplified a bit; see [**PEP 302**](https://www.python.org/dev/peps/pep-0302) \[https://www.python.org/dev/peps/pep-0302\] for the full details):
```
for mp in sys.meta_path:
loader = mp(fullname)
if loader is not None:
<module> = loader.load_module(fullname)
for path in sys.path:
for hook in sys.path_hooks:
try:
importer = hook(path)
except ImportError:
# ImportError, so try the other path hooks
pass
else:
loader = importer.find_module(fullname)
<module> = loader.load_module(fullname)
# Not found!
raise ImportError
```
参见
[**PEP 302**](https://www.python.org/dev/peps/pep-0302) \[https://www.python.org/dev/peps/pep-0302\] - New Import HooksWritten by Just van Rossum and Paul Moore. Implemented by Just van Rossum.
## PEP 305: Comma-separated Files
Comma-separated files are a format frequently used for exporting data from databases and spreadsheets. Python 2.3 adds a parser for comma-separated files.
Comma-separated format is deceptively simple at first glance:
```
Costs,150,200,3.95
```
Read a line and call `line.split(',')`: what could be simpler? But toss in string data that can contain commas, and things get more complicated:
```
"Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"
```
A big ugly regular expression can parse this, but using the new [`csv`](../library/csv.xhtml#module-csv "csv: Write and read tabular data to and from delimited files.")package is much simpler:
```
import csv
input = open('datafile', 'rb')
reader = csv.reader(input)
for line in reader:
print line
```
The `reader()` function takes a number of different options. The field separator isn't limited to the comma and can be changed to any character, and so can the quoting and line-ending characters.
Different dialects of comma-separated files can be defined and registered; currently there are two dialects, both used by Microsoft Excel. A separate [`csv.writer`](../library/csv.xhtml#csv.writer "csv.writer") class will generate comma-separated files from a succession of tuples or lists, quoting strings that contain the delimiter.
参见
[**PEP 305**](https://www.python.org/dev/peps/pep-0305) \[https://www.python.org/dev/peps/pep-0305\] - CSV 文件 APIWritten and implemented by Kevin Altis, Dave Cole, Andrew McNamara, Skip Montanaro, Cliff Wells.
## PEP 307: Pickle Enhancements
The [`pickle`](../library/pickle.xhtml#module-pickle "pickle: Convert Python objects to streams of bytes and back.") and `cPickle` modules received some attention during the 2.3 development cycle. In 2.2, new-style classes could be pickled without difficulty, but they weren't pickled very compactly; [**PEP 307**](https://www.python.org/dev/peps/pep-0307) \[https://www.python.org/dev/peps/pep-0307\] quotes a trivial example where a new-style class results in a pickled string three times longer than that for a classic class.
The solution was to invent a new pickle protocol. The [`pickle.dumps()`](../library/pickle.xhtml#pickle.dumps "pickle.dumps")function has supported a text-or-binary flag for a long time. In 2.3, this flag is redefined from a Boolean to an integer: 0 is the old text-mode pickle format, 1 is the old binary format, and now 2 is a new 2.3-specific format. A new constant, [`pickle.HIGHEST_PROTOCOL`](../library/pickle.xhtml#pickle.HIGHEST_PROTOCOL "pickle.HIGHEST_PROTOCOL"), can be used to select the fanciest protocol available.
Unpickling is no longer considered a safe operation. 2.2's [`pickle`](../library/pickle.xhtml#module-pickle "pickle: Convert Python objects to streams of bytes and back.")provided hooks for trying to prevent unsafe classes from being unpickled (specifically, a `__safe_for_unpickling__` attribute), but none of this code was ever audited and therefore it's all been ripped out in 2.3. You should not unpickle untrusted data in any version of Python.
To reduce the pickling overhead for new-style classes, a new interface for customizing pickling was added using three special methods: [`__getstate__()`](../library/pickle.xhtml#object.__getstate__ "object.__getstate__"), [`__setstate__()`](../library/pickle.xhtml#object.__setstate__ "object.__setstate__"), and [`__getnewargs__()`](../library/pickle.xhtml#object.__getnewargs__ "object.__getnewargs__"). Consult [**PEP 307**](https://www.python.org/dev/peps/pep-0307) \[https://www.python.org/dev/peps/pep-0307\] for the full semantics of these methods.
As a way to compress pickles yet further, it's now possible to use integer codes instead of long strings to identify pickled classes. The Python Software Foundation will maintain a list of standardized codes; there's also a range of codes for private use. Currently no codes have been specified.
参见
[**PEP 307**](https://www.python.org/dev/peps/pep-0307) \[https://www.python.org/dev/peps/pep-0307\] - Extensions to the pickle protocolWritten and implemented by Guido van Rossum and Tim Peters.
## Extended Slices
Ever since Python 1.4, the slicing syntax has supported an optional third "step" or "stride" argument. For example, these are all legal Python syntax: `L[1:10:2]`, `L[:-1:1]`, `L[::-1]`. This was added to Python at the request of the developers of Numerical Python, which uses the third argument extensively. However, Python's built-in list, tuple, and string sequence types have never supported this feature, raising a [`TypeError`](../library/exceptions.xhtml#TypeError "TypeError") if you tried it. Michael Hudson contributed a patch to fix this shortcoming.
For example, you can now easily extract the elements of a list that have even indexes:
```
>>> L = range(10)
>>> L[::2]
[0, 2, 4, 6, 8]
```
Negative values also work to make a copy of the same list in reverse order:
```
>>> L[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
```
This also works for tuples, arrays, and strings:
```
>>> s='abcd'
>>> s[::2]
'ac'
>>> s[::-1]
'dcba'
```
If you have a mutable sequence such as a list or an array you can assign to or delete an extended slice, but there are some differences between assignment to extended and regular slices. Assignment to a regular slice can be used to change the length of the sequence:
```
>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]
```
Extended slices aren't this flexible. When assigning to an extended slice, the list on the right hand side of the statement must contain the same number of items as the slice it is replacing:
```
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2
```
Deletion is more straightforward:
```
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> del a[::2]
>>> a
[1, 3]
```
One can also now pass slice objects to the [`__getitem__()`](../reference/datamodel.xhtml#object.__getitem__ "object.__getitem__") methods of the built-in sequences:
```
>>> range(10).__getitem__(slice(0, 5, 2))
[0, 2, 4]
```
Or use slice objects directly in subscripts:
```
>>> range(10)[slice(0, 5, 2)]
[0, 2, 4]
```
To simplify implementing sequences that support extended slicing, slice objects now have a method `indices(length)` which, given the length of a sequence, returns a `(start, stop, step)` tuple that can be passed directly to [`range()`](../library/stdtypes.xhtml#range "range"). `indices()` handles omitted and out-of-bounds indices in a manner consistent with regular slices (and this innocuous phrase hides a welter of confusing details!). The method is intended to be used like this:
```
class FakeSeq:
...
def calc_item(self, i):
...
def __getitem__(self, item):
if isinstance(item, slice):
indices = item.indices(len(self))
return FakeSeq([self.calc_item(i) for i in range(*indices)])
else:
return self.calc_item(i)
```
From this example you can also see that the built-in [`slice`](../library/functions.xhtml#slice "slice") object is now the type object for the slice type, and is no longer a function. This is consistent with Python 2.2, where [`int`](../library/functions.xhtml#int "int"), [`str`](../library/stdtypes.xhtml#str "str"), etc., underwent the same change.
## 其他语言特性修改
Here are all of the changes that Python 2.3 makes to the core Python language.
- The [`yield`](../reference/simple_stmts.xhtml#yield) statement is now always a keyword, as described in section [PEP 255: Simple Generators](#section-generators) of this document.
- A new built-in function [`enumerate()`](../library/functions.xhtml#enumerate "enumerate") was added, as described in section [PEP 279: enumerate()](#section-enumerate) of this document.
- Two new constants, [`True`](../library/constants.xhtml#True "True") and [`False`](../library/constants.xhtml#False "False") were added along with the built-in [`bool`](../library/functions.xhtml#bool "bool") type, as described in section [PEP 285: A Boolean Type](#section-bool) of this document.
- The [`int()`](../library/functions.xhtml#int "int") type constructor will now return a long integer instead of raising an [`OverflowError`](../library/exceptions.xhtml#OverflowError "OverflowError") when a string or floating-point number is too large to fit into an integer. This can lead to the paradoxical result that `isinstance(int(expression), int)` is false, but that seems unlikely to cause problems in practice.
- Built-in types now support the extended slicing syntax, as described in section [Extended Slices](#section-slices) of this document.
- A new built-in function, `sum(iterable, start=0)`, adds up the numeric items in the iterable object and returns their sum. [`sum()`](../library/functions.xhtml#sum "sum") only accepts numbers, meaning that you can't use it to concatenate a bunch of strings. (Contributed by Alex Martelli.)
- `list.insert(pos, value)` used to insert *value* at the front of the list when *pos* was negative. The behaviour has now been changed to be consistent with slice indexing, so when *pos* is -1 the value will be inserted before the last element, and so forth.
- `list.index(value)`, which searches for *value* within the list and returns its index, now takes optional *start* and *stop* arguments to limit the search to only part of the list.
- Dictionaries have a new method, `pop(key[, *default*])`, that returns the value corresponding to *key* and removes that key/value pair from the dictionary. If the requested key isn't present in the dictionary, *default* is returned if it's specified and [`KeyError`](../library/exceptions.xhtml#KeyError "KeyError") raised if it isn't.
```
>>> d = {1:2}
>>> d
{1: 2}
>>> d.pop(4)
Traceback (most recent call last):
File "stdin", line 1, in ?
KeyError: 4
>>> d.pop(1)
2
>>> d.pop(1)
Traceback (most recent call last):
File "stdin", line 1, in ?
KeyError: 'pop(): dictionary is empty'
>>> d
{}
>>>
```
There's also a new class method, `dict.fromkeys(iterable, value)`, that creates a dictionary with keys taken from the supplied iterator *iterable* and all values set to *value*, defaulting to `None`.
(Patches contributed by Raymond Hettinger.)
Also, the [`dict()`](../library/stdtypes.xhtml#dict "dict") constructor now accepts keyword arguments to simplify creating small dictionaries:
```
>>> dict(red=1, blue=2, green=3, black=4)
{'blue': 2, 'black': 4, 'green': 3, 'red': 1}
```
(Contributed by Just van Rossum.)
- The [`assert`](../reference/simple_stmts.xhtml#assert) statement no longer checks the `__debug__` flag, so you can no longer disable assertions by assigning to `__debug__`. Running Python with the [`-O`](../using/cmdline.xhtml#cmdoption-o) switch will still generate code that doesn't execute any assertions.
- Most type objects are now callable, so you can use them to create new objects such as functions, classes, and modules. (This means that the `new` module can be deprecated in a future Python version, because you can now use the type objects available in the [`types`](../library/types.xhtml#module-types "types: Names for built-in types.") module.) For example, you can create a new module object with the following code:
```
>>> import types
>>> m = types.ModuleType('abc','docstring')
>>> m
<module 'abc' (built-in)>
>>> m.__doc__
'docstring'
```
- A new warning, [`PendingDeprecationWarning`](../library/exceptions.xhtml#PendingDeprecationWarning "PendingDeprecationWarning") was added to indicate features which are in the process of being deprecated. The warning will *not* be printed by default. To check for use of features that will be deprecated in the future, supply [`-Walways::PendingDeprecationWarning::`](../using/cmdline.xhtml#cmdoption-w) on the command line or use [`warnings.filterwarnings()`](../library/warnings.xhtml#warnings.filterwarnings "warnings.filterwarnings").
- The process of deprecating string-based exceptions, as in
```
raise "Error
occurred"
```
, has begun. Raising a string will now trigger [`PendingDeprecationWarning`](../library/exceptions.xhtml#PendingDeprecationWarning "PendingDeprecationWarning").
- Using `None` as a variable name will now result in a [`SyntaxWarning`](../library/exceptions.xhtml#SyntaxWarning "SyntaxWarning")warning. In a future version of Python, `None` may finally become a keyword.
- The `xreadlines()` method of file objects, introduced in Python 2.1, is no longer necessary because files now behave as their own iterator. `xreadlines()` was originally introduced as a faster way to loop over all the lines in a file, but now you can simply write `for line in file_obj`. File objects also have a new read-only `encoding` attribute that gives the encoding used by the file; Unicode strings written to the file will be automatically converted to bytes using the given encoding.
- The method resolution order used by new-style classes has changed, though you'll only notice the difference if you have a really complicated inheritance hierarchy. Classic classes are unaffected by this change. Python 2.2 originally used a topological sort of a class's ancestors, but 2.3 now uses the C3 algorithm as described in the paper ["A Monotonic Superclass Linearization for Dylan"](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.3910) \[http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.3910\]. To understand the motivation for this change, read Michele Simionato's article ["Python 2.3 Method Resolution Order"](http://www.phyast.pitt.edu/~micheles/mro.html) \[http://www.phyast.pitt.edu/~micheles/mro.html\], or read the thread on python-dev starting with the message at <https://mail.python.org/pipermail/python-dev/2002-October/029035.html>. Samuele Pedroni first pointed out the problem and also implemented the fix by coding the C3 algorithm.
- Python runs multithreaded programs by switching between threads after executing N bytecodes. The default value for N has been increased from 10 to 100 bytecodes, speeding up single-threaded applications by reducing the switching overhead. Some multithreaded applications may suffer slower response time, but that's easily fixed by setting the limit back to a lower number using `sys.setcheckinterval(N)`. The limit can be retrieved with the new [`sys.getcheckinterval()`](../library/sys.xhtml#sys.getcheckinterval "sys.getcheckinterval") function.
- One minor but far-reaching change is that the names of extension types defined by the modules included with Python now contain the module and a `'.'` in front of the type name. For example, in Python 2.2, if you created a socket and printed its `__class__`, you'd get this output:
```
>>> s = socket.socket()
>>> s.__class__
<type 'socket'>
```
In 2.3, you get this:
```
>>> s.__class__
<type '_socket.socket'>
```
- One of the noted incompatibilities between old- and new-style classes has been removed: you can now assign to the [`__name__`](../library/stdtypes.xhtml#definition.__name__ "definition.__name__") and [`__bases__`](../library/stdtypes.xhtml#class.__bases__ "class.__bases__")attributes of new-style classes. There are some restrictions on what can be assigned to [`__bases__`](../library/stdtypes.xhtml#class.__bases__ "class.__bases__") along the lines of those relating to assigning to an instance's [`__class__`](../library/stdtypes.xhtml#instance.__class__ "instance.__class__") attribute.
### String Changes
- The [`in`](../reference/expressions.xhtml#in) operator now works differently for strings. Previously, when evaluating `X in Y` where *X* and *Y* are strings, *X* could only be a single character. That's now changed; *X* can be a string of any length, and `X in Y`will return [`True`](../library/constants.xhtml#True "True") if *X* is a substring of *Y*. If *X* is the empty string, the result is always [`True`](../library/constants.xhtml#True "True").
```
>>> 'ab' in 'abcd'
True
>>> 'ad' in 'abcd'
False
>>> '' in 'abcd'
True
```
Note that this doesn't tell you where the substring starts; if you need that information, use the `find()` string method.
- The `strip()`, `lstrip()`, and `rstrip()` string methods now have an optional argument for specifying the characters to strip. The default is still to remove all whitespace characters:
```
>>> ' abc '.strip()
'abc'
>>> '><><abc<><><>'.strip('<>')
'abc'
>>> '><><abc<><><>\n'.strip('<>')
'abc<><><>\n'
>>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
u'\u4001abc'
>>>
```
(Suggested by Simon Brunning and implemented by Walter Dörwald.)
- The `startswith()` and `endswith()` string methods now accept negative numbers for the *start* and *end* parameters.
- Another new string method is `zfill()`, originally a function in the [`string`](../library/string.xhtml#module-string "string: Common string operations.") module. `zfill()` pads a numeric string with zeros on the left until it's the specified width. Note that the `%` operator is still more flexible and powerful than `zfill()`.
```
>>> '45'.zfill(4)
'0045'
>>> '12345'.zfill(4)
'12345'
>>> 'goofy'.zfill(6)
'0goofy'
```
(Contributed by Walter Dörwald.)
- A new type object, `basestring`, has been added. Both 8-bit strings and Unicode strings inherit from this type, so `isinstance(obj, basestring)` will return [`True`](../library/constants.xhtml#True "True") for either kind of string. It's a completely abstract type, so you can't create `basestring` instances.
- Interned strings are no longer immortal and will now be garbage-collected in the usual way when the only reference to them is from the internal dictionary of interned strings. (Implemented by Oren Tirosh.)
### 性能优化
- The creation of new-style class instances has been made much faster; they're now faster than classic classes!
- The `sort()` method of list objects has been extensively rewritten by Tim Peters, and the implementation is significantly faster.
- Multiplication of large long integers is now much faster thanks to an implementation of Karatsuba multiplication, an algorithm that scales better than the O(n\*n) required for the grade-school multiplication algorithm. (Original patch by Christopher A. Craig, and significantly reworked by Tim Peters.)
- The `SET_LINENO` opcode is now gone. This may provide a small speed increase, depending on your compiler's idiosyncrasies. See section [Other Changes and Fixes](#section-other) for a longer explanation. (Removed by Michael Hudson.)
- `xrange()` objects now have their own iterator, making
```
for i in
xrange(n)
```
slightly faster than `for i in range(n)`. (Patch by Raymond Hettinger.)
- A number of small rearrangements have been made in various hotspots to improve performance, such as inlining a function or removing some code. (Implemented mostly by GvR, but lots of people have contributed single changes.)
The net result of the 2.3 optimizations is that Python 2.3 runs the pystone benchmark around 25% faster than Python 2.2.
## New, Improved, and Deprecated Modules
As usual, Python's standard library received a number of enhancements and bug fixes. Here's a partial list of the most notable changes, sorted alphabetically by module name. Consult the `Misc/NEWS` file in the source tree for a more complete list of changes, or look through the CVS logs for all the details.
- The [`array`](../library/array.xhtml#module-array "array: Space efficient arrays of uniformly typed numeric values.") module now supports arrays of Unicode characters using the `'u'` format character. Arrays also now support using the `+=` assignment operator to add another array's contents, and the `*=` assignment operator to repeat an array. (Contributed by Jason Orendorff.)
- The `bsddb` module has been replaced by version 4.1.6 of the [PyBSDDB](http://pybsddb.sourceforge.net) \[http://pybsddb.sourceforge.net\] package, providing a more complete interface to the transactional features of the BerkeleyDB library.
The old version of the module has been renamed to `bsddb185` and is no longer built automatically; you'll have to edit `Modules/Setup` to enable it. Note that the new `bsddb` package is intended to be compatible with the old module, so be sure to file bugs if you discover any incompatibilities. When upgrading to Python 2.3, if the new interpreter is compiled with a new version of the underlying BerkeleyDB library, you will almost certainly have to convert your database files to the new version. You can do this fairly easily with the new scripts `db2pickle.py` and `pickle2db.py` which you will find in the distribution's `Tools/scripts` directory. If you've already been using the PyBSDDB package and importing it as `bsddb3`, you will have to change your `import` statements to import it as `bsddb`.
- The new [`bz2`](../library/bz2.xhtml#module-bz2 "bz2: Interfaces for bzip2 compression and decompression.") module is an interface to the bz2 data compression library. bz2-compressed data is usually smaller than corresponding [`zlib`](../library/zlib.xhtml#module-zlib "zlib: Low-level interface to compression and decompression routines compatible with gzip.")-compressed data. (Contributed by Gustavo Niemeyer.)
- A set of standard date/time types has been added in the new [`datetime`](../library/datetime.xhtml#module-datetime "datetime: Basic date and time types.")module. See the following section for more details.
- The Distutils `Extension` class now supports an extra constructor argument named *depends* for listing additional source files that an extension depends on. This lets Distutils recompile the module if any of the dependency files are modified. For example, if `sampmodule.c` includes the header file `sample.h`, you would create the `Extension` object like this:
```
ext = Extension("samp",
sources=["sampmodule.c"],
depends=["sample.h"])
```
Modifying `sample.h` would then cause the module to be recompiled. (Contributed by Jeremy Hylton.)
- Other minor changes to Distutils: it now checks for the `CC`, `CFLAGS`, `CPP`, `LDFLAGS`, and `CPPFLAGS`environment variables, using them to override the settings in Python's configuration (contributed by Robert Weber).
- Previously the [`doctest`](../library/doctest.xhtml#module-doctest "doctest: Test pieces of code within docstrings.") module would only search the docstrings of public methods and functions for test cases, but it now also examines private ones as well. The `DocTestSuite()` function creates a [`unittest.TestSuite`](../library/unittest.xhtml#unittest.TestSuite "unittest.TestSuite") object from a set of [`doctest`](../library/doctest.xhtml#module-doctest "doctest: Test pieces of code within docstrings.") tests.
- The new `gc.get_referents(object)` function returns a list of all the objects referenced by *object*.
- The [`getopt`](../library/getopt.xhtml#module-getopt "getopt: Portable parser for command line options; support both short and long option names.") module gained a new function, `gnu_getopt()`, that supports the same arguments as the existing [`getopt()`](../library/getopt.xhtml#module-getopt "getopt: Portable parser for command line options; support both short and long option names.") function but uses GNU-style scanning mode. The existing [`getopt()`](../library/getopt.xhtml#module-getopt "getopt: Portable parser for command line options; support both short and long option names.") stops processing options as soon as a non-option argument is encountered, but in GNU-style mode processing continues, meaning that options and arguments can be mixed. For example:
```
>>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
([('-f', 'filename')], ['output', '-v'])
>>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
([('-f', 'filename'), ('-v', '')], ['output'])
```
(Contributed by Peter Åstrand.)
- The [`grp`](../library/grp.xhtml#module-grp "grp: The group database (getgrnam() and friends). (Unix)"), [`pwd`](../library/pwd.xhtml#module-pwd "pwd: The password database (getpwnam() and friends). (Unix)"), and [`resource`](../library/resource.xhtml#module-resource "resource: An interface to provide resource usage information on the current process. (Unix)") modules now return enhanced tuples:
```
>>> import grp
>>> g = grp.getgrnam('amk')
>>> g.gr_name, g.gr_gid
('amk', 500)
```
- The [`gzip`](../library/gzip.xhtml#module-gzip "gzip: Interfaces for gzip compression and decompression using file objects.") module can now handle files exceeding 2 GiB.
- The new [`heapq`](../library/heapq.xhtml#module-heapq "heapq: Heap queue algorithm (a.k.a. priority queue).") module contains an implementation of a heap queue algorithm. A heap is an array-like data structure that keeps items in a partially sorted order such that, for every index *k*,
```
heap[k] <=
heap[2*k+1]
```
and `heap[k] <= heap[2*k+2]`. This makes it quick to remove the smallest item, and inserting a new item while maintaining the heap property is O(lg n). (See <https://xlinux.nist.gov/dads//HTML/priorityque.html> for more information about the priority queue data structure.)
The [`heapq`](../library/heapq.xhtml#module-heapq "heapq: Heap queue algorithm (a.k.a. priority queue).") module provides `heappush()` and `heappop()` functions for adding and removing items while maintaining the heap property on top of some other mutable Python sequence type. Here's an example that uses a Python list:
```
>>> import heapq
>>> heap = []
>>> for item in [3, 7, 5, 11, 1]:
... heapq.heappush(heap, item)
...
>>> heap
[1, 3, 5, 11, 7]
>>> heapq.heappop(heap)
1
>>> heapq.heappop(heap)
3
>>> heap
[5, 7, 11]
```
(Contributed by Kevin O'Connor.)
- The IDLE integrated development environment has been updated using the code from the IDLEfork project (<http://idlefork.sourceforge.net>). The most notable feature is that the code being developed is now executed in a subprocess, meaning that there's no longer any need for manual `reload()` operations. IDLE's core code has been incorporated into the standard library as the `idlelib` package.
- The [`imaplib`](../library/imaplib.xhtml#module-imaplib "imaplib: IMAP4 protocol client (requires sockets).") module now supports IMAP over SSL. (Contributed by Piers Lauder and Tino Lange.)
- The [`itertools`](../library/itertools.xhtml#module-itertools "itertools: Functions creating iterators for efficient looping.") contains a number of useful functions for use with iterators, inspired by various functions provided by the ML and Haskell languages. For example, `itertools.ifilter(predicate, iterator)` returns all elements in the iterator for which the function `predicate()` returns [`True`](../library/constants.xhtml#True "True"), and `itertools.repeat(obj, N)` returns `obj` *N* times. There are a number of other functions in the module; see the package's reference documentation for details. (Contributed by Raymond Hettinger.)
- Two new functions in the [`math`](../library/math.xhtml#module-math "math: Mathematical functions (sin() etc.).") module, `degrees(rads)` and `radians(degs)`, convert between radians and degrees. Other functions in the [`math`](../library/math.xhtml#module-math "math: Mathematical functions (sin() etc.).") module such as [`math.sin()`](../library/math.xhtml#math.sin "math.sin") and [`math.cos()`](../library/math.xhtml#math.cos "math.cos") have always required input values measured in radians. Also, an optional *base* argument was added to [`math.log()`](../library/math.xhtml#math.log "math.log") to make it easier to compute logarithms for bases other than `e` and `10`. (Contributed by Raymond Hettinger.)
- Several new POSIX functions (`getpgid()`, `killpg()`, `lchown()`, `loadavg()`, `major()`, `makedev()`, `minor()`, and `mknod()`) were added to the [`posix`](../library/posix.xhtml#module-posix "posix: The most common POSIX system calls (normally used via module os). (Unix)") module that underlies the [`os`](../library/os.xhtml#module-os "os: Miscellaneous operating system interfaces.") module. (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S. Otkidach.)
- In the [`os`](../library/os.xhtml#module-os "os: Miscellaneous operating system interfaces.") module, the `*stat()` family of functions can now report fractions of a second in a timestamp. Such time stamps are represented as floats, similar to the value returned by [`time.time()`](../library/time.xhtml#time.time "time.time").
During testing, it was found that some applications will break if time stamps are floats. For compatibility, when using the tuple interface of the `stat_result` time stamps will be represented as integers. When using named fields (a feature first introduced in Python 2.2), time stamps are still represented as integers, unless `os.stat_float_times()` is invoked to enable float return values:
```
>>> os.stat("/tmp").st_mtime
1034791200
>>> os.stat_float_times(True)
>>> os.stat("/tmp").st_mtime
1034791200.6335014
```
In Python 2.4, the default will change to always returning floats.
Application developers should enable this feature only if all their libraries work properly when confronted with floating point time stamps, or if they use the tuple API. If used, the feature should be activated on an application level instead of trying to enable it on a per-use basis.
- The [`optparse`](../library/optparse.xhtml#module-optparse "optparse: Command-line option parsing library. (已移除)") module contains a new parser for command-line arguments that can convert option values to a particular Python type and will automatically generate a usage message. See the following section for more details.
- The old and never-documented `linuxaudiodev` module has been deprecated, and a new version named [`ossaudiodev`](../library/ossaudiodev.xhtml#module-ossaudiodev "ossaudiodev: Access to OSS-compatible audio devices. (Linux, FreeBSD)") has been added. The module was renamed because the OSS sound drivers can be used on platforms other than Linux, and the interface has also been tidied and brought up to date in various ways. (Contributed by Greg Ward and Nicholas FitzRoy-Dale.)
- The new [`platform`](../library/platform.xhtml#module-platform "platform: Retrieves as much platform identifying data as possible.") module contains a number of functions that try to determine various properties of the platform you're running on. There are functions for getting the architecture, CPU type, the Windows OS version, and even the Linux distribution version. (Contributed by Marc-André Lemburg.)
- The parser objects provided by the `pyexpat` module can now optionally buffer character data, resulting in fewer calls to your character data handler and therefore faster performance. Setting the parser object's `buffer_text` attribute to [`True`](../library/constants.xhtml#True "True") will enable buffering.
- The `sample(population, k)` function was added to the [`random`](../library/random.xhtml#module-random "random: Generate pseudo-random numbers with various common distributions.")module. *population* is a sequence or `xrange` object containing the elements of a population, and `sample()` chooses *k* elements from the population without replacing chosen elements. *k* can be any value up to `len(population)`. For example:
```
>>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
>>> random.sample(days, 3) # Choose 3 elements
['St', 'Sn', 'Th']
>>> random.sample(days, 7) # Choose 7 elements
['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
>>> random.sample(days, 7) # Choose 7 again
['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
>>> random.sample(days, 8) # Can't choose eight
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "random.py", line 414, in sample
raise ValueError, "sample larger than population"
ValueError: sample larger than population
>>> random.sample(xrange(1,10000,2), 10) # Choose ten odd nos. under 10000
[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]
```
The [`random`](../library/random.xhtml#module-random "random: Generate pseudo-random numbers with various common distributions.") module now uses a new algorithm, the Mersenne Twister, implemented in C. It's faster and more extensively studied than the previous algorithm.
(All changes contributed by Raymond Hettinger.)
- The [`readline`](../library/readline.xhtml#module-readline "readline: GNU readline support for Python. (Unix)") module also gained a number of new functions: `get_history_item()`, `get_current_history_length()`, and `redisplay()`.
- The `rexec` and `Bastion` modules have been declared dead, and attempts to import them will fail with a [`RuntimeError`](../library/exceptions.xhtml#RuntimeError "RuntimeError"). New-style classes provide new ways to break out of the restricted execution environment provided by `rexec`, and no one has interest in fixing them or time to do so. If you have applications using `rexec`, rewrite them to use something else.
(Sticking with Python 2.2 or 2.1 will not make your applications any safer because there are known bugs in the `rexec` module in those versions. To repeat: if you're using `rexec`, stop using it immediately.)
- The `rotor` module has been deprecated because the algorithm it uses for encryption is not believed to be secure. If you need encryption, use one of the several AES Python modules that are available separately.
- The [`shutil`](../library/shutil.xhtml#module-shutil "shutil: High-level file operations, including copying.") module gained a `move(src, dest)` function that recursively moves a file or directory to a new location.
- Support for more advanced POSIX signal handling was added to the [`signal`](../library/signal.xhtml#module-signal "signal: Set handlers for asynchronous events.")but then removed again as it proved impossible to make it work reliably across platforms.
- The [`socket`](../library/socket.xhtml#module-socket "socket: Low-level networking interface.") module now supports timeouts. You can call the `settimeout(t)` method on a socket object to set a timeout of *t* seconds. Subsequent socket operations that take longer than *t* seconds to complete will abort and raise a [`socket.timeout`](../library/socket.xhtml#socket.timeout "socket.timeout") exception.
The original timeout implementation was by Tim O'Malley. Michael Gilfix integrated it into the Python [`socket`](../library/socket.xhtml#module-socket "socket: Low-level networking interface.") module and shepherded it through a lengthy review. After the code was checked in, Guido van Rossum rewrote parts of it. (This is a good example of a collaborative development process in action.)
- On Windows, the [`socket`](../library/socket.xhtml#module-socket "socket: Low-level networking interface.") module now ships with Secure Sockets Layer (SSL) support.
- The value of the C `PYTHON_API_VERSION` macro is now exposed at the Python level as `sys.api_version`. The current exception can be cleared by calling the new `sys.exc_clear()` function.
- The new [`tarfile`](../library/tarfile.xhtml#module-tarfile "tarfile: Read and write tar-format archive files.") module allows reading from and writing to **tar**-format archive files. (Contributed by Lars Gustäbel.)
- The new [`textwrap`](../library/textwrap.xhtml#module-textwrap "textwrap: Text wrapping and filling") module contains functions for wrapping strings containing paragraphs of text. The `wrap(text, width)` function takes a string and returns a list containing the text split into lines of no more than the chosen width. The `fill(text, width)` function returns a single string, reformatted to fit into lines no longer than the chosen width. (As you can guess, `fill()` is built on top of `wrap()`. For example:
```
>>> import textwrap
>>> paragraph = "Not a whit, we defy augury: ... more text ..."
>>> textwrap.wrap(paragraph, 60)
["Not a whit, we defy augury: there's a special providence in",
"the fall of a sparrow. If it be now, 'tis not to come; if it",
...]
>>> print textwrap.fill(paragraph, 35)
Not a whit, we defy augury: there's
a special providence in the fall of
a sparrow. If it be now, 'tis not
to come; if it be not to come, it
will be now; if it be not now, yet
it will come: the readiness is all.
>>>
```
The module also contains a `TextWrapper` class that actually implements the text wrapping strategy. Both the `TextWrapper` class and the `wrap()` and `fill()` functions support a number of additional keyword arguments for fine-tuning the formatting; consult the module's documentation for details. (Contributed by Greg Ward.)
- The `thread` and [`threading`](../library/threading.xhtml#module-threading "threading: Thread-based parallelism.") modules now have companion modules, `dummy_thread` and [`dummy_threading`](../library/dummy_threading.xhtml#module-dummy_threading "dummy_threading: Drop-in replacement for the threading module."), that provide a do-nothing implementation of the `thread` module's interface for platforms where threads are not supported. The intention is to simplify thread-aware modules (ones that *don't* rely on threads to run) by putting the following code at the top:
```
try:
import threading as _threading
except ImportError:
import dummy_threading as _threading
```
In this example, `_threading` is used as the module name to make it clear that the module being used is not necessarily the actual [`threading`](../library/threading.xhtml#module-threading "threading: Thread-based parallelism.")module. Code can call functions and use classes in `_threading` whether or not threads are supported, avoiding an [`if`](../reference/compound_stmts.xhtml#if) statement and making the code slightly clearer. This module will not magically make multithreaded code run without threads; code that waits for another thread to return or to do something will simply hang forever.
- The [`time`](../library/time.xhtml#module-time "time: Time access and conversions.") module's `strptime()` function has long been an annoyance because it uses the platform C library's `strptime()` implementation, and different platforms sometimes have odd bugs. Brett Cannon contributed a portable implementation that's written in pure Python and should behave identically on all platforms.
- The new [`timeit`](../library/timeit.xhtml#module-timeit "timeit: Measure the execution time of small code snippets.") module helps measure how long snippets of Python code take to execute. The `timeit.py` file can be run directly from the command line, or the module's `Timer` class can be imported and used directly. Here's a short example that figures out whether it's faster to convert an 8-bit string to Unicode by appending an empty Unicode string to it or by using the `unicode()` function:
```
import timeit
timer1 = timeit.Timer('unicode("abc")')
timer2 = timeit.Timer('"abc" + u""')
# Run three trials
print timer1.repeat(repeat=3, number=100000)
print timer2.repeat(repeat=3, number=100000)
# On my laptop this outputs:
# [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]
# [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]
```
- The `Tix` module has received various bug fixes and updates for the current version of the Tix package.
- The `Tkinter` module now works with a thread-enabled version of Tcl. Tcl's threading model requires that widgets only be accessed from the thread in which they're created; accesses from another thread can cause Tcl to panic. For certain Tcl interfaces, `Tkinter` will now automatically avoid this when a widget is accessed from a different thread by marshalling a command, passing it to the correct thread, and waiting for the results. Other interfaces can't be handled automatically but `Tkinter` will now raise an exception on such an access so that you can at least find out about the problem. See <https://mail.python.org/pipermail/python-dev/2002-December/031107.html> for a more detailed explanation of this change. (Implemented by Martin von Löwis.)
- Calling Tcl methods through `_tkinter` no longer returns only strings. Instead, if Tcl returns other objects those objects are converted to their Python equivalent, if one exists, or wrapped with a `_tkinter.Tcl_Obj`object if no Python equivalent exists. This behavior can be controlled through the `wantobjects()` method of `tkapp` objects.
When using `_tkinter` through the `Tkinter` module (as most Tkinter applications will), this feature is always activated. It should not cause compatibility problems, since Tkinter would always convert string results to Python types where possible.
If any incompatibilities are found, the old behavior can be restored by setting the `wantobjects` variable in the `Tkinter` module to false before creating the first `tkapp` object.
```
import Tkinter
Tkinter.wantobjects = 0
```
Any breakage caused by this change should be reported as a bug.
- The `UserDict` module has a new `DictMixin` class which defines all dictionary methods for classes that already have a minimum mapping interface. This greatly simplifies writing classes that need to be substitutable for dictionaries, such as the classes in the [`shelve`](../library/shelve.xhtml#module-shelve "shelve: Python object persistence.")module.
Adding the mix-in as a superclass provides the full dictionary interface whenever the class defines [`__getitem__()`](../reference/datamodel.xhtml#object.__getitem__ "object.__getitem__"), [`__setitem__()`](../reference/datamodel.xhtml#object.__setitem__ "object.__setitem__"), [`__delitem__()`](../reference/datamodel.xhtml#object.__delitem__ "object.__delitem__"), and `keys()`. For example:
```
>>> import UserDict
>>> class SeqDict(UserDict.DictMixin):
... """Dictionary lookalike implemented with lists."""
... def __init__(self):
... self.keylist = []
... self.valuelist = []
... def __getitem__(self, key):
... try:
... i = self.keylist.index(key)
... except ValueError:
... raise KeyError
... return self.valuelist[i]
... def __setitem__(self, key, value):
... try:
... i = self.keylist.index(key)
... self.valuelist[i] = value
... except ValueError:
... self.keylist.append(key)
... self.valuelist.append(value)
... def __delitem__(self, key):
... try:
... i = self.keylist.index(key)
... except ValueError:
... raise KeyError
... self.keylist.pop(i)
... self.valuelist.pop(i)
... def keys(self):
... return list(self.keylist)
...
>>> s = SeqDict()
>>> dir(s) # See that other dictionary methods are implemented
['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
'__init__', '__iter__', '__len__', '__module__', '__repr__',
'__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
'setdefault', 'update', 'valuelist', 'values']
```
(Contributed by Raymond Hettinger.)
- The DOM implementation in [`xml.dom.minidom`](../library/xml.dom.minidom.xhtml#module-xml.dom.minidom "xml.dom.minidom: Minimal Document Object Model (DOM) implementation.") can now generate XML output in a particular encoding by providing an optional encoding argument to the `toxml()` and `toprettyxml()` methods of DOM nodes.
- The `xmlrpclib` module now supports an XML-RPC extension for handling nil data values such as Python's `None`. Nil values are always supported on unmarshalling an XML-RPC response. To generate requests containing `None`, you must supply a true value for the *allow\_none* parameter when creating a `Marshaller` instance.
- The new `DocXMLRPCServer` module allows writing self-documenting XML-RPC servers. Run it in demo mode (as a program) to see it in action. Pointing the Web browser to the RPC server produces pydoc-style documentation; pointing xmlrpclib to the server allows invoking the actual methods. (Contributed by Brian Quinlan.)
- Support for internationalized domain names (RFCs 3454, 3490, 3491, and 3492) has been added. The "idna" encoding can be used to convert between a Unicode domain name and the ASCII-compatible encoding (ACE) of that name.
```
>{}>{}> u"www.Alliancefrançaise.nu".encode("idna")
'www.xn--alliancefranaise-npb.nu'
```
The [`socket`](../library/socket.xhtml#module-socket "socket: Low-level networking interface.") module has also been extended to transparently convert Unicode hostnames to the ACE version before passing them to the C library. Modules that deal with hostnames such as `httplib` and [`ftplib`](../library/ftplib.xhtml#module-ftplib "ftplib: FTP protocol client (requires sockets).")) also support Unicode host names; `httplib` also sends HTTP `Host`headers using the ACE version of the domain name. [`urllib`](../library/urllib.xhtml#module-urllib "urllib") supports Unicode URLs with non-ASCII host names as long as the `path` part of the URL is ASCII only.
To implement this change, the [`stringprep`](../library/stringprep.xhtml#module-stringprep "stringprep: String preparation, as per RFC 3453") module, the `mkstringprep`tool and the `punycode` encoding have been added.
### Date/Time Type
Date and time types suitable for expressing timestamps were added as the [`datetime`](../library/datetime.xhtml#module-datetime "datetime: Basic date and time types.") module. The types don't support different calendars or many fancy features, and just stick to the basics of representing time.
The three primary types are: `date`, representing a day, month, and year; [`time`](../library/datetime.xhtml#datetime.time "datetime.time"), consisting of hour, minute, and second; and [`datetime`](../library/datetime.xhtml#datetime.datetime "datetime.datetime"), which contains all the attributes of both `date` and [`time`](../library/datetime.xhtml#datetime.time "datetime.time"). There's also a `timedelta` class representing differences between two points in time, and time zone logic is implemented by classes inheriting from the abstract `tzinfo` class.
You can create instances of `date` and [`time`](../library/datetime.xhtml#datetime.time "datetime.time") by either supplying keyword arguments to the appropriate constructor, e.g. `datetime.date(year=1972, month=10, day=15)`, or by using one of a number of class methods. For example, the `date.today()` class method returns the current local date.
Once created, instances of the date/time classes are all immutable. There are a number of methods for producing formatted strings from objects:
```
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.isoformat()
'2002-12-30T21:27:03.994956'
>>> now.ctime() # Only available on date, datetime
'Mon Dec 30 21:27:03 2002'
>>> now.strftime('%Y %d %b')
'2002 30 Dec'
```
The `replace()` method allows modifying one or more fields of a `date` or [`datetime`](../library/datetime.xhtml#datetime.datetime "datetime.datetime") instance, returning a new instance:
```
>>> d = datetime.datetime.now()
>>> d
datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
>>> d.replace(year=2001, hour = 12)
datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
>>>
```
Instances can be compared, hashed, and converted to strings (the result is the same as that of `isoformat()`). `date` and [`datetime`](../library/datetime.xhtml#datetime.datetime "datetime.datetime")instances can be subtracted from each other, and added to `timedelta`instances. The largest missing feature is that there's no standard library support for parsing strings and getting back a `date` or [`datetime`](../library/datetime.xhtml#datetime.datetime "datetime.datetime").
For more information, refer to the module's reference documentation. (Contributed by Tim Peters.)
### The optparse Module
The [`getopt`](../library/getopt.xhtml#module-getopt "getopt: Portable parser for command line options; support both short and long option names.") module provides simple parsing of command-line arguments. The new [`optparse`](../library/optparse.xhtml#module-optparse "optparse: Command-line option parsing library. (已移除)") module (originally named Optik) provides more elaborate command-line parsing that follows the Unix conventions, automatically creates the output for `--help`, and can perform different actions for different options.
You start by creating an instance of `OptionParser` and telling it what your program's options are.
```
import sys
from optparse import OptionParser
op = OptionParser()
op.add_option('-i', '--input',
action='store', type='string', dest='input',
help='set input filename')
op.add_option('-l', '--length',
action='store', type='int', dest='length',
help='set maximum length of output')
```
Parsing a command line is then done by calling the `parse_args()` method.
```
options, args = op.parse_args(sys.argv[1:])
print options
print args
```
This returns an object containing all of the option values, and a list of strings containing the remaining arguments.
Invoking the script with the various arguments now works as you'd expect it to. Note that the length argument is automatically converted to an integer.
```
$ ./python opt.py -i data arg1
<Values at 0x400cad4c: {'input': 'data', 'length': None}>
['arg1']
$ ./python opt.py --input=data --length=4
<Values at 0x400cad2c: {'input': 'data', 'length': 4}>
[]
$
```
The help message is automatically generated for you:
```
$ ./python opt.py --help
usage: opt.py [options]
options:
-h, --help show this help message and exit
-iINPUT, --input=INPUT
set input filename
-lLENGTH, --length=LENGTH
set maximum length of output
$
```
See the module's documentation for more details.
Optik was written by Greg Ward, with suggestions from the readers of the Getopt SIG.
## Pymalloc: A Specialized Object Allocator
Pymalloc, a specialized object allocator written by Vladimir Marangozov, was a feature added to Python 2.1. Pymalloc is intended to be faster than the system `malloc()` and to have less memory overhead for allocation patterns typical of Python programs. The allocator uses C's `malloc()` function to get large pools of memory and then fulfills smaller memory requests from these pools.
In 2.1 and 2.2, pymalloc was an experimental feature and wasn't enabled by default; you had to explicitly enable it when compiling Python by providing the `--with-pymalloc` option to the **configure** script. In 2.3, pymalloc has had further enhancements and is now enabled by default; you'll have to supply `--without-pymalloc` to disable it.
This change is transparent to code written in Python; however, pymalloc may expose bugs in C extensions. Authors of C extension modules should test their code with pymalloc enabled, because some incorrect code may cause core dumps at runtime.
There's one particularly common error that causes problems. There are a number of memory allocation functions in Python's C API that have previously just been aliases for the C library's `malloc()` and `free()`, meaning that if you accidentally called mismatched functions the error wouldn't be noticeable. When the object allocator is enabled, these functions aren't aliases of `malloc()` and `free()` any more, and calling the wrong function to free memory may get you a core dump. For example, if memory was allocated using [`PyObject_Malloc()`](../c-api/memory.xhtml#c.PyObject_Malloc "PyObject_Malloc"), it has to be freed using [`PyObject_Free()`](../c-api/memory.xhtml#c.PyObject_Free "PyObject_Free"), not `free()`. A few modules included with Python fell afoul of this and had to be fixed; doubtless there are more third-party modules that will have the same problem.
As part of this change, the confusing multiple interfaces for allocating memory have been consolidated down into two API families. Memory allocated with one family must not be manipulated with functions from the other family. There is one family for allocating chunks of memory and another family of functions specifically for allocating Python objects.
- To allocate and free an undistinguished chunk of memory use the "raw memory" family: [`PyMem_Malloc()`](../c-api/memory.xhtml#c.PyMem_Malloc "PyMem_Malloc"), [`PyMem_Realloc()`](../c-api/memory.xhtml#c.PyMem_Realloc "PyMem_Realloc"), and [`PyMem_Free()`](../c-api/memory.xhtml#c.PyMem_Free "PyMem_Free").
- The "object memory" family is the interface to the pymalloc facility described above and is biased towards a large number of "small" allocations: [`PyObject_Malloc()`](../c-api/memory.xhtml#c.PyObject_Malloc "PyObject_Malloc"), [`PyObject_Realloc()`](../c-api/memory.xhtml#c.PyObject_Realloc "PyObject_Realloc"), and [`PyObject_Free()`](../c-api/memory.xhtml#c.PyObject_Free "PyObject_Free").
- To allocate and free Python objects, use the "object" family [`PyObject_New()`](../c-api/allocation.xhtml#c.PyObject_New "PyObject_New"), [`PyObject_NewVar()`](../c-api/allocation.xhtml#c.PyObject_NewVar "PyObject_NewVar"), and [`PyObject_Del()`](../c-api/allocation.xhtml#c.PyObject_Del "PyObject_Del").
Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging features to catch memory overwrites and doubled frees in both extension modules and in the interpreter itself. To enable this support, compile a debugging version of the Python interpreter by running **configure** with `--with-pydebug`.
To aid extension writers, a header file `Misc/pymemcompat.h` is distributed with the source to Python 2.3 that allows Python extensions to use the 2.3 interfaces to memory allocation while compiling against any version of Python since 1.5.2. You would copy the file from Python's source distribution and bundle it with the source of your extension.
参见
<https://hg.python.org/cpython/file/default/Objects/obmalloc.c>For the full details of the pymalloc implementation, see the comments at the top of the file `Objects/obmalloc.c` in the Python source code. The above link points to the file within the python.org SVN browser.
## Build and C API Changes
Changes to Python's build process and to the C API include:
- The cycle detection implementation used by the garbage collection has proven to be stable, so it's now been made mandatory. You can no longer compile Python without it, and the `--with-cycle-gc` switch to **configure** has been removed.
- Python can now optionally be built as a shared library (`libpython2.3.so`) by supplying `--enable-shared` when running Python's **configure** script. (Contributed by Ondrej Palkovsky.)
- The `DL_EXPORT` and `DL_IMPORT` macros are now deprecated. Initialization functions for Python extension modules should now be declared using the new macro `PyMODINIT_FUNC`, while the Python core will generally use the `PyAPI_FUNC` and `PyAPI_DATA` macros.
- The interpreter can be compiled without any docstrings for the built-in functions and modules by supplying `--without-doc-strings` to the **configure** script. This makes the Python executable about 10% smaller, but will also mean that you can't get help for Python's built-ins. (Contributed by Gustavo Niemeyer.)
- The `PyArg_NoArgs()` macro is now deprecated, and code that uses it should be changed. For Python 2.2 and later, the method definition table can specify the [`METH_NOARGS`](../c-api/structures.xhtml#METH_NOARGS "METH_NOARGS") flag, signalling that there are no arguments, and the argument checking can then be removed. If compatibility with pre-2.2 versions of Python is important, the code could use
```
PyArg_ParseTuple(args,
"")
```
instead, but this will be slower than using [`METH_NOARGS`](../c-api/structures.xhtml#METH_NOARGS "METH_NOARGS").
- [`PyArg_ParseTuple()`](../c-api/arg.xhtml#c.PyArg_ParseTuple "PyArg_ParseTuple") accepts new format characters for various sizes of unsigned integers: `B` for `unsigned char`, `H` for
```
unsigned
short int
```
, `I` for `unsigned int`, and `K` for
```
unsigned
long long
```
.
- A new function, `PyObject_DelItemString(mapping, char *key)` was added as shorthand for `PyObject_DelItem(mapping, PyString_New(key))`.
- File objects now manage their internal string buffer differently, increasing it exponentially when needed. This results in the benchmark tests in `Lib/test/test_bufio.py` speeding up considerably (from 57 seconds to 1.7 seconds, according to one measurement).
- It's now possible to define class and static methods for a C extension type by setting either the [`METH_CLASS`](../c-api/structures.xhtml#METH_CLASS "METH_CLASS") or [`METH_STATIC`](../c-api/structures.xhtml#METH_STATIC "METH_STATIC") flags in a method's [`PyMethodDef`](../c-api/structures.xhtml#c.PyMethodDef "PyMethodDef") structure.
- Python now includes a copy of the Expat XML parser's source code, removing any dependence on a system version or local installation of Expat.
- If you dynamically allocate type objects in your extension, you should be aware of a change in the rules relating to the `__module__` and [`__name__`](../library/stdtypes.xhtml#definition.__name__ "definition.__name__") attributes. In summary, you will want to ensure the type's dictionary contains a `'__module__'` key; making the module name the part of the type name leading up to the final period will no longer have the desired effect. For more detail, read the API reference documentation or the source.
### Port-Specific Changes
Support for a port to IBM's OS/2 using the EMX runtime environment was merged into the main Python source tree. EMX is a POSIX emulation layer over the OS/2 system APIs. The Python port for EMX tries to support all the POSIX-like capability exposed by the EMX runtime, and mostly succeeds; `fork()` and [`fcntl()`](../library/fcntl.xhtml#module-fcntl "fcntl: The fcntl() and ioctl() system calls. (Unix)") are restricted by the limitations of the underlying emulation layer. The standard OS/2 port, which uses IBM's Visual Age compiler, also gained support for case-sensitive import semantics as part of the integration of the EMX port into CVS. (Contributed by Andrew MacIntyre.)
On MacOS, most toolbox modules have been weaklinked to improve backward compatibility. This means that modules will no longer fail to load if a single routine is missing on the current OS version. Instead calling the missing routine will raise an exception. (Contributed by Jack Jansen.)
The RPM spec files, found in the `Misc/RPM/` directory in the Python source distribution, were updated for 2.3. (Contributed by Sean Reifschneider.)
Other new platforms now supported by Python include AtheOS (<http://www.atheos.cx/>), GNU/Hurd, and OpenVMS.
## Other Changes and Fixes
As usual, there were a bunch of other improvements and bugfixes scattered throughout the source tree. A search through the CVS change logs finds there were 523 patches applied and 514 bugs fixed between Python 2.2 and 2.3. Both figures are likely to be underestimates.
Some of the more notable changes are:
- If the [`PYTHONINSPECT`](../using/cmdline.xhtml#envvar-PYTHONINSPECT) environment variable is set, the Python interpreter will enter the interactive prompt after running a Python program, as if Python had been invoked with the [`-i`](../using/cmdline.xhtml#cmdoption-i) option. The environment variable can be set before running the Python interpreter, or it can be set by the Python program as part of its execution.
- The `regrtest.py` script now provides a way to allow "all resources except *foo*." A resource name passed to the `-u` option can now be prefixed with a hyphen (`'-'`) to mean "remove this resource." For example, the option '`-uall,-bsddb`' could be used to enable the use of all resources except `bsddb`.
- The tools used to build the documentation now work under Cygwin as well as Unix.
- The `SET_LINENO` opcode has been removed. Back in the mists of time, this opcode was needed to produce line numbers in tracebacks and support trace functions (for, e.g., [`pdb`](../library/pdb.xhtml#module-pdb "pdb: The Python debugger for interactive interpreters.")). Since Python 1.5, the line numbers in tracebacks have been computed using a different mechanism that works with "python -O". For Python 2.3 Michael Hudson implemented a similar scheme to determine when to call the trace function, removing the need for `SET_LINENO`entirely.
It would be difficult to detect any resulting difference from Python code, apart from a slight speed up when Python is run without [`-O`](../using/cmdline.xhtml#cmdoption-o).
C extensions that access the `f_lineno` field of frame objects should instead call `PyCode_Addr2Line(f->f_code, f->f_lasti)`. This will have the added effect of making the code work as desired under "python -O" in earlier versions of Python.
A nifty new feature is that trace functions can now assign to the `f_lineno` attribute of frame objects, changing the line that will be executed next. A `jump` command has been added to the [`pdb`](../library/pdb.xhtml#module-pdb "pdb: The Python debugger for interactive interpreters.") debugger taking advantage of this new feature. (Implemented by Richie Hindle.)
## Porting to Python 2.3
This section lists previously described changes that may require changes to your code:
- [`yield`](../reference/simple_stmts.xhtml#yield) is now always a keyword; if it's used as a variable name in your code, a different name must be chosen.
- For strings *X* and *Y*, `X in Y` now works if *X* is more than one character long.
- The [`int()`](../library/functions.xhtml#int "int") type constructor will now return a long integer instead of raising an [`OverflowError`](../library/exceptions.xhtml#OverflowError "OverflowError") when a string or floating-point number is too large to fit into an integer.
- If you have Unicode strings that contain 8-bit characters, you must declare the file's encoding (UTF-8, Latin-1, or whatever) by adding a comment to the top of the file. See section [PEP 263: Source Code Encodings](#section-encodings) for more information.
- Calling Tcl methods through `_tkinter` no longer returns only strings. Instead, if Tcl returns other objects those objects are converted to their Python equivalent, if one exists, or wrapped with a `_tkinter.Tcl_Obj`object if no Python equivalent exists.
- Large octal and hex literals such as `0xffffffff` now trigger a [`FutureWarning`](../library/exceptions.xhtml#FutureWarning "FutureWarning"). Currently they're stored as 32-bit numbers and result in a negative value, but in Python 2.4 they'll become positive long integers.
There are a few ways to fix this warning. If you really need a positive number, just add an `L` to the end of the literal. If you're trying to get a 32-bit integer with low bits set and have previously used an expression such as
```
~(1
<< 31)
```
, it's probably clearest to start with all bits set and clear the desired upper bits. For example, to clear just the top bit (bit 31), you could write `0xffffffffL &~(1L<<31)`.
- You can no longer disable assertions by assigning to `__debug__`.
- The Distutils `setup()` function has gained various new keyword arguments such as *depends*. Old versions of the Distutils will abort if passed unknown keywords. A solution is to check for the presence of the new `get_distutil_options()` function in your `setup.py` and only uses the new keywords with a version of the Distutils that supports them:
```
from distutils import core
kw = {'sources': 'foo.c', ...}
if hasattr(core, 'get_distutil_options'):
kw['depends'] = ['foo.h']
ext = Extension(**kw)
```
- Using `None` as a variable name will now result in a [`SyntaxWarning`](../library/exceptions.xhtml#SyntaxWarning "SyntaxWarning")warning.
- Names of extension types defined by the modules included with Python now contain the module and a `'.'` in front of the type name.
## Acknowledgements
The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Jeff Bauer, Simon Brunning, Brett Cannon, Michael Chermside, Andrew Dalke, Scott David Daniels, Fred L. Drake, Jr., David Fraser, Kelly Gerber, Raymond Hettinger, Michael Hudson, Chris Lambert, Detlef Lannert, Martin von Löwis, Andrew MacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, Roman Suzi, Jason Tishler, Just van Rossum.
### 导航
- [索引](../genindex.xhtml "总目录")
- [模块](../py-modindex.xhtml "Python 模块索引") |
- [下一页](2.2.xhtml "What's New in Python 2.2") |
- [上一页](2.4.xhtml "What's New in Python 2.4") |
- ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png)
- [Python](https://www.python.org/) »
- zh\_CN 3.7.3 [文档](../index.xhtml) »
- [Python 有什么新变化?](index.xhtml) »
- $('.inline-search').show(0); |
© [版权所有](../copyright.xhtml) 2001-2019, Python Software Foundation.
Python 软件基金会是一个非盈利组织。 [请捐助。](https://www.python.org/psf/donations/)
最后更新于 5月 21, 2019. [发现了问题](../bugs.xhtml)?
使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 创建。
- Python文档内容
- Python 有什么新变化?
- Python 3.7 有什么新变化
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- C API 的改变
- 构建的改变
- 性能优化
- 其他 CPython 实现的改变
- 已弃用的 Python 行为
- 已弃用的 Python 模块、函数和方法
- 已弃用的 C API 函数和类型
- 平台支持的移除
- API 与特性的移除
- 移除的模块
- Windows 专属的改变
- 移植到 Python 3.7
- Python 3.7.1 中的重要变化
- Python 3.7.2 中的重要变化
- Python 3.6 有什么新变化A
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- 性能优化
- Build and C API Changes
- 其他改进
- 弃用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要变化
- Python 3.6.4 中的重要变化
- Python 3.6.5 中的重要变化
- Python 3.6.7 中的重要变化
- Python 3.5 有什么新变化
- 摘要 - 发布重点
- 新的特性
- 其他语言特性修改
- 新增模块
- 改进的模块
- Other module-level changes
- 性能优化
- Build and C API Changes
- 弃用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 发布重点
- 新的特性
- 新增模块
- 改进的模块
- CPython Implementation Changes
- 弃用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 发布重点
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他语言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模块
- 改进的模块
- 性能优化
- Build and C API Changes
- 弃用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- 多线程
- 性能优化
- Unicode
- Codecs
- 文档
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- 性能优化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他语言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新变化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他语言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他语言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他语言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推导式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最终版
- Python 3.7.3 发布候选版 1
- Python 3.7.2 最终版
- Python 3.7.2 发布候选版 1
- Python 3.7.1 最终版
- Python 3.7.1 RC 2版本
- Python 3.7.1 发布候选版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 课前甜点
- 使用 Python 解释器
- 调用解释器
- 解释器的运行环境
- Python 的非正式介绍
- Python 作为计算器使用
- 走向编程的第一步
- 其他流程控制工具
- if 语句
- for 语句
- range() 函数
- break 和 continue 语句,以及循环中的 else 子句
- pass 语句
- 定义函数
- 函数定义的更多形式
- 小插曲:编码风格
- 数据结构
- 列表的更多特性
- del 语句
- 元组和序列
- 集合
- 字典
- 循环的技巧
- 深入条件控制
- 序列和其它类型的比较
- 模块
- 有关模块的更多信息
- 标准模块
- dir() 函数
- 包
- 输入输出
- 更漂亮的输出格式
- 读写文件
- 错误和异常
- 语法错误
- 异常
- 处理异常
- 抛出异常
- 用户自定义异常
- 定义清理操作
- 预定义的清理操作
- 类
- 名称和对象
- Python 作用域和命名空间
- 初探类
- 补充说明
- 继承
- 私有变量
- 杂项说明
- 迭代器
- 生成器
- 生成器表达式
- 标准库简介
- 操作系统接口
- 文件通配符
- 命令行参数
- 错误输出重定向和程序终止
- 字符串模式匹配
- 数学
- 互联网访问
- 日期和时间
- 数据压缩
- 性能测量
- 质量控制
- 自带电池
- 标准库简介 —— 第二部分
- 格式化输出
- 模板
- 使用二进制数据记录格式
- 多线程
- 日志
- 弱引用
- 用于操作列表的工具
- 十进制浮点运算
- 虚拟环境和包
- 概述
- 创建虚拟环境
- 使用pip管理包
- 接下来?
- 交互式编辑和编辑历史
- Tab 补全和编辑历史
- 默认交互式解释器的替代品
- 浮点算术:争议和限制
- 表示性错误
- 附录
- 交互模式
- 安装和使用 Python
- 命令行与环境
- 命令行
- 环境变量
- 在Unix平台中使用Python
- 获取最新版本的Python
- 构建Python
- 与Python相关的路径和文件
- 杂项
- 编辑器和集成开发环境
- 在Windows上使用 Python
- 完整安装程序
- Microsoft Store包
- nuget.org 安装包
- 可嵌入的包
- 替代捆绑包
- 配置Python
- 适用于Windows的Python启动器
- 查找模块
- 附加模块
- 在Windows上编译Python
- 其他平台
- 在苹果系统上使用 Python
- 获取和安装 MacPython
- IDE
- 安装额外的 Python 包
- Mac 上的图形界面编程
- 在 Mac 上分发 Python 应用程序
- 其他资源
- Python 语言参考
- 概述
- 其他实现
- 标注
- 词法分析
- 行结构
- 其他形符
- 标识符和关键字
- 字面值
- 运算符
- 分隔符
- 数据模型
- 对象、值与类型
- 标准类型层级结构
- 特殊方法名称
- 协程
- 执行模型
- 程序的结构
- 命名与绑定
- 异常
- 导入系统
- importlib
- 包
- 搜索
- 加载
- 基于路径的查找器
- 替换标准导入系统
- Package Relative Imports
- 有关 main 的特殊事项
- 开放问题项
- 参考文献
- 表达式
- 算术转换
- 原子
- 原型
- await 表达式
- 幂运算符
- 一元算术和位运算
- 二元算术运算符
- 移位运算
- 二元位运算
- 比较运算
- 布尔运算
- 条件表达式
- lambda 表达式
- 表达式列表
- 求值顺序
- 运算符优先级
- 简单语句
- 表达式语句
- 赋值语句
- assert 语句
- pass 语句
- del 语句
- return 语句
- yield 语句
- raise 语句
- break 语句
- continue 语句
- import 语句
- global 语句
- nonlocal 语句
- 复合语句
- if 语句
- while 语句
- for 语句
- try 语句
- with 语句
- 函数定义
- 类定义
- 协程
- 最高层级组件
- 完整的 Python 程序
- 文件输入
- 交互式输入
- 表达式输入
- 完整的语法规范
- Python 标准库
- 概述
- 可用性注释
- 内置函数
- 内置常量
- 由 site 模块添加的常量
- 内置类型
- 逻辑值检测
- 布尔运算 — and, or, not
- 比较
- 数字类型 — int, float, complex
- 迭代器类型
- 序列类型 — list, tuple, range
- 文本序列类型 — str
- 二进制序列类型 — bytes, bytearray, memoryview
- 集合类型 — set, frozenset
- 映射类型 — dict
- 上下文管理器类型
- 其他内置类型
- 特殊属性
- 内置异常
- 基类
- 具体异常
- 警告
- 异常层次结构
- 文本处理服务
- string — 常见的字符串操作
- re — 正则表达式操作
- 模块 difflib 是一个计算差异的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 数据库
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函数
- 二进制数据服务
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 数据类型
- datetime — 基础日期/时间数据类型
- calendar — General calendar-related functions
- collections — 容器数据类型
- collections.abc — 容器的抽象基类
- heapq — 堆队列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 浅层 (shallow) 和深层 (deep) 复制操作
- pprint — 数据美化输出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 数字和数学模块
- numbers — 数字的抽象基类
- math — 数学函数
- cmath — Mathematical functions for complex numbers
- decimal — 十进制定点和浮点运算
- fractions — 分数
- random — 生成伪随机数
- statistics — Mathematical statistics functions
- 函数式编程模块
- itertools — 为高效循环而创建迭代器的函数
- functools — 高阶函数和可调用对象上的操作
- operator — 标准运算符替代函数
- 文件和目录访问
- pathlib — 面向对象的文件系统路径
- os.path — 常见路径操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路径操作函数
- 数据持久化
- pickle —— Python 对象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 数据库 DB-API 2.0 接口模块
- 数据压缩和存档
- zlib — 与 gzip 兼容的压缩
- gzip — 对 gzip 格式的支持
- bz2 — 对 bzip2 压缩算法的支持
- lzma — 用 LZMA 算法压缩
- zipfile — 在 ZIP 归档中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件读写
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服务
- hashlib — 安全哈希与消息摘要
- hmac — 基于密钥的消息验证
- secrets — Generate secure random numbers for managing secrets
- 通用操作系统服务
- os — 操作系统接口模块
- io — 处理流的核心工具
- time — 时间的访问和转换
- argparse — 命令行选项、参数和子命令解析器
- getopt — C-style parser for command line options
- 模块 logging — Python 的日志记录工具
- logging.config — 日志记录配置
- logging.handlers — Logging handlers
- getpass — 便携式密码输入工具
- curses — 终端字符单元显示的处理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函数库
- 并发执行
- threading — 基于线程的并行
- multiprocessing — 基于进程的并行
- concurrent 包
- concurrent.futures — 启动并行任务
- subprocess — 子进程管理
- sched — 事件调度器
- queue — 一个同步的队列类
- _thread — 底层多线程 API
- _dummy_thread — _thread 的替代模块
- dummy_threading — 可直接替代 threading 模块。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 网络和进程间通信
- asyncio — 异步 I/O
- socket — 底层网络接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高级 I/O 复用库
- asyncore — 异步socket处理器
- asynchat — 异步 socket 指令/响应 处理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互联网数据处理
- email — 电子邮件与 MIME 处理包
- json — JSON 编码和解码器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 数据编码
- binhex — 对binhex4文件进行编码和解码
- binascii — 二进制和 ASCII 码互转
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 结构化标记处理工具
- html — 超文本标记语言支持
- html.parser — 简单的 HTML 和 XHTML 解析器
- html.entities — HTML 一般实体的定义
- XML处理模块
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互联网协议和支持
- webbrowser — 方便的Web浏览器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 处理模块
- urllib.request — 用于打开 URL 的可扩展库
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模块
- http.client — HTTP协议客户端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP协议客户端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服务器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服务端与客户端模块
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒体服务
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 读写 Sun AU 文件
- wave — 读写WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推测图像类型
- sndhdr — 推测声音文件的类型
- ossaudiodev — Access to OSS-compatible audio devices
- 国际化
- gettext — 多语种国际化服务
- locale — 国际化服务
- 程序框架
- turtle — 海龟绘图
- cmd — 支持面向行的命令解释器
- shlex — Simple lexical analysis
- Tk图形用户界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滚动文字控件
- IDLE
- 其他图形用户界面(GUI)包
- 开发工具
- typing — 类型标注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 单元测试框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自动将 Python 2 代码转为 Python 3 代码
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 调试和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 测量小代码片段的执行时间
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 软件打包和分发
- distutils — 构建和安装 Python 模块
- ensurepip — Bootstrapping the pip installer
- venv — 创建虚拟环境
- zipapp — Manage executable Python zip archives
- Python运行时服务
- sys — 系统相关的参数和函数
- sysconfig — Provide access to Python's configuration information
- builtins — 内建对象
- main — 顶层脚本环境
- warnings — Warning control
- dataclasses — 数据类
- contextlib — Utilities for with-statement contexts
- abc — 抽象基类
- atexit — 退出处理器
- traceback — Print or retrieve a stack traceback
- future — Future 语句定义
- gc — 垃圾回收器接口
- inspect — 检查对象
- site — Site-specific configuration hook
- 自定义 Python 解释器
- code — Interpreter base classes
- codeop — Compile Python code
- 导入模块
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找脚本使用的模块
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 语言服务
- parser — Access Python parse trees
- ast — 抽象语法树
- symtable — Access to the compiler's symbol tables
- symbol — 与 Python 解析树一起使用的常量
- token — 与Python解析树一起使用的常量
- keyword — 检验Python关键字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊缩进检测
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字节码反汇编器
- pickletools — Tools for pickle developers
- 杂项服务
- formatter — Generic output formatting
- Windows系统相关模块
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注册表访问
- winsound — Sound-playing interface for Windows
- Unix 专有服务
- posix — The most common POSIX system calls
- pwd — 用户密码数据库
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 终端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 库例程
- 被取代的模块
- optparse — Parser for command line options
- imp — Access the import internals
- 未创建文档的模块
- 平台特定模块
- 扩展和嵌入 Python 解释器
- 推荐的第三方工具
- 不使用第三方工具创建扩展
- 使用 C 或 C++ 扩展 Python
- 自定义扩展类型:教程
- 定义扩展类型:已分类主题
- 构建C/C++扩展
- 在Windows平台编译C和C++扩展
- 在更大的应用程序中嵌入 CPython 运行时
- Embedding Python in Another Application
- Python/C API 参考手册
- 概述
- 代码标准
- 包含文件
- 有用的宏
- 对象、类型和引用计数
- 异常
- 嵌入Python
- 调试构建
- 稳定的应用程序二进制接口
- The Very High Level Layer
- Reference Counting
- 异常处理
- Printing and clearing
- 抛出异常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 标准异常
- 标准警告类别
- 工具
- 操作系统实用程序
- 系统功能
- 过程控制
- 导入模块
- Data marshalling support
- 语句解释及变量编译
- 字符串转换与格式化
- 反射
- 编解码器注册与支持功能
- 抽象对象层
- Object Protocol
- 数字协议
- Sequence Protocol
- Mapping Protocol
- 迭代器协议
- 缓冲协议
- Old Buffer Protocol
- 具体的对象层
- 基本对象
- 数值对象
- 序列对象
- 容器对象
- 函数对象
- 其他对象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置变量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 内存管理
- 概述
- 原始内存接口
- Memory Interface
- 对象分配器
- 默认内存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 对象实现支持
- 在堆中分配对象
- Common Object Structures
- Type 对象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使对象类型支持循环垃圾回收
- API 和 ABI 版本管理
- 分发 Python 模块
- 关键术语
- 开源许可与协作
- 安装工具
- 阅读指南
- 我该如何...?
- ...为我的项目选择一个名字?
- ...创建和分发二进制扩展?
- 安装 Python 模块
- 关键术语
- 基本使用
- 我应如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安装 pip ?
- ... 只为当前用户安装软件包?
- ... 安装科学计算类 Python 软件包?
- ... 使用并行安装的多个 Python 版本?
- 常见的安装问题
- 在 Linux 的系统 Python 版本上安装
- 未安装 pip
- 安装二进制编译扩展
- Python 常用指引
- 将 Python 2 代码迁移到 Python 3
- 简要说明
- 详情
- 将扩展模块移植到 Python 3
- 条件编译
- 对象API的更改
- 模块初始化和状态
- CObject 替换为 Capsule
- 其他选项
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 实现描述器
- 摘要
- 定义和简介
- 描述器协议
- 发起调用描述符
- 描述符示例
- Properties
- 函数和方法
- Static Methods and Class Methods
- 函数式编程指引
- 概述
- 迭代器
- 生成器表达式和列表推导式
- 生成器
- 内置函数
- itertools 模块
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文献
- 日志 HOWTO
- 日志基础教程
- 进阶日志教程
- 日志级别
- 有用的处理程序
- 记录日志中引发的异常
- 使用任意对象作为消息
- 优化
- 日志操作手册
- 在多个模块中使用日志
- 在多线程中使用日志
- 使用多个日志处理器和多种格式化
- 在多个地方记录日志
- 日志服务器配置示例
- 处理日志处理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正则表达式HOWTO
- 概述
- 简单模式
- 使用正则表达式
- 更多模式能力
- 修改字符串
- 常见问题
- 反馈
- 套接字编程指南
- 套接字
- 创建套接字
- 使用一个套接字
- 断开连接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 关键函数
- Operator 模块函数
- 升序和降序
- 排序稳定性和排序复杂度
- 使用装饰-排序-去装饰的旧方法
- 使用 cmp 参数的旧方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包获取网络资源
- 概述
- Fetching URLs
- 处理异常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 脚注
- Argparse 教程
- 概念
- 基础
- 位置参数介绍
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模块介绍
- 创建 Address/Network/Interface 对象
- 审查 Address/Network/Interface 对象
- Network 作为 Address 列表
- 比较
- 将IP地址与其他模块一起使用
- 实例创建失败时获取更多详细信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 检测CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常见问题
- Python常见问题
- 一般信息
- 现实世界中的 Python
- 编程常见问题
- 一般问题
- 核心语言
- 数字和字符串
- 性能
- 序列(元组/列表)
- 对象
- 模块
- 设计和历史常见问题
- 为什么Python使用缩进来分组语句?
- 为什么简单的算术运算得到奇怪的结果?
- 为什么浮点计算不准确?
- 为什么Python字符串是不可变的?
- 为什么必须在方法定义和调用中显式使用“self”?
- 为什么不能在表达式中赋值?
- 为什么Python对某些功能(例如list.index())使用方法来实现,而其他功能(例如len(List))使用函数实现?
- 为什么 join()是一个字符串方法而不是列表或元组方法?
- 异常有多快?
- 为什么Python中没有switch或case语句?
- 难道不能在解释器中模拟线程,而非得依赖特定于操作系统的线程实现吗?
- 为什么lambda表达式不能包含语句?
- 可以将Python编译为机器代码,C或其他语言吗?
- Python如何管理内存?
- 为什么CPython不使用更传统的垃圾回收方案?
- CPython退出时为什么不释放所有内存?
- 为什么有单独的元组和列表数据类型?
- 列表是如何在CPython中实现的?
- 字典是如何在CPython中实现的?
- 为什么字典key必须是不可变的?
- 为什么 list.sort() 没有返回排序列表?
- 如何在Python中指定和实施接口规范?
- 为什么没有goto?
- 为什么原始字符串(r-strings)不能以反斜杠结尾?
- 为什么Python没有属性赋值的“with”语句?
- 为什么 if/while/def/class语句需要冒号?
- 为什么Python在列表和元组的末尾允许使用逗号?
- 代码库和插件 FAQ
- 通用的代码库问题
- 通用任务
- 线程相关
- 输入输出
- 网络 / Internet 编程
- 数据库
- 数学和数字
- 扩展/嵌入常见问题
- 可以使用C语言中创建自己的函数吗?
- 可以使用C++语言中创建自己的函数吗?
- C很难写,有没有其他选择?
- 如何从C执行任意Python语句?
- 如何从C中评估任意Python表达式?
- 如何从Python对象中提取C的值?
- 如何使用Py_BuildValue()创建任意长度的元组?
- 如何从C调用对象的方法?
- 如何捕获PyErr_Print()(或打印到stdout / stderr的任何内容)的输出?
- 如何从C访问用Python编写的模块?
- 如何从Python接口到C ++对象?
- 我使用Setup文件添加了一个模块,为什么make失败了?
- 如何调试扩展?
- 我想在Linux系统上编译一个Python模块,但是缺少一些文件。为什么?
- 如何区分“输入不完整”和“输入无效”?
- 如何找到未定义的g++符号__builtin_new或__pure_virtual?
- 能否创建一个对象类,其中部分方法在C中实现,而其他方法在Python中实现(例如通过继承)?
- Python在Windows上的常见问题
- 我怎样在Windows下运行一个Python程序?
- 我怎么让 Python 脚本可执行?
- 为什么有时候 Python 程序会启动缓慢?
- 我怎样使用Python脚本制作可执行文件?
- *.pyd 文件和DLL文件相同吗?
- 我怎样将Python嵌入一个Windows程序?
- 如何让编辑器不要在我的 Python 源代码中插入 tab ?
- 如何在不阻塞的情况下检查按键?
- 图形用户界面(GUI)常见问题
- 图形界面常见问题
- Python 是否有平台无关的图形界面工具包?
- 有哪些Python的GUI工具是某个平台专用的?
- 有关Tkinter的问题
- “为什么我的电脑上安装了 Python ?”
- 什么是Python?
- 为什么我的电脑上安装了 Python ?
- 我能删除 Python 吗?
- 术语对照表
- 文档说明
- Python 文档贡献者
- 解决 Bug
- 文档错误
- 使用 Python 的错误追踪系统
- 开始为 Python 贡献您的知识
- 版权
- 历史和许可证
- 软件历史
- 访问Python或以其他方式使用Python的条款和条件
- Python 3.7.3 的 PSF 许可协议
- Python 2.0 的 BeOpen.com 许可协议
- Python 1.6.1 的 CNRI 许可协议
- Python 0.9.0 至 1.2 的 CWI 许可协议
- 集成软件的许可和认可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec