summaryrefslogtreecommitdiffstats
path: root/Doc/whatsnew
diff options
context:
space:
mode:
authorGeorg Brandl <georg@python.org>2008-11-07 08:56:27 (GMT)
committerGeorg Brandl <georg@python.org>2008-11-07 08:56:27 (GMT)
commit4aef703c45c7eea0f00a35a64fafc675f3ef98a2 (patch)
treeb0ce71f3d8d3c7706204dbe7622dff87f7089a97 /Doc/whatsnew
parent939582fd0629deedb95309e564a3d6a3a12dc87c (diff)
downloadcpython-4aef703c45c7eea0f00a35a64fafc675f3ef98a2.zip
cpython-4aef703c45c7eea0f00a35a64fafc675f3ef98a2.tar.gz
cpython-4aef703c45c7eea0f00a35a64fafc675f3ef98a2.tar.bz2
Merged revisions 66801,66803-66804,66813,66854-66856,66866,66870-66872,66874,66887,66903,66905,66911,66913,66927,66932,66938,66942,66962,66964,66973-66974,66977,66992,66998-66999,67002,67005,67007,67028,67040-67041,67044,67070,67089,67091,67101,67117-67119,67123-67124 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk ................ r66801 | andrew.kuchling | 2008-10-04 23:51:59 +0200 (Sat, 04 Oct 2008) | 1 line Punctuation fix; expand dict.update docstring to be clearer ................ r66803 | benjamin.peterson | 2008-10-05 00:15:31 +0200 (Sun, 05 Oct 2008) | 1 line fix typo ................ r66804 | andrew.kuchling | 2008-10-05 02:11:56 +0200 (Sun, 05 Oct 2008) | 1 line #1415508 from Rocky Bernstein: add docstrings for enable_interspersed_args(), disable_interspersed_args() ................ r66813 | andrew.kuchling | 2008-10-06 14:07:04 +0200 (Mon, 06 Oct 2008) | 3 lines Per Greg Ward, optparse is no longer being externally maintained. I'll look at the bugs in the Optik bug tracker and copy them to the Python bug tracker if they're still relevant. ................ r66854 | georg.brandl | 2008-10-08 19:20:20 +0200 (Wed, 08 Oct 2008) | 2 lines #4059: patch up some sqlite docs. ................ r66855 | georg.brandl | 2008-10-08 19:30:55 +0200 (Wed, 08 Oct 2008) | 2 lines #4058: fix some whatsnew markup. ................ r66856 | georg.brandl | 2008-10-08 20:47:17 +0200 (Wed, 08 Oct 2008) | 3 lines #3935: properly support list subclasses in the C impl. of bisect. Patch reviewed by Raymond. ................ r66866 | benjamin.peterson | 2008-10-09 22:54:43 +0200 (Thu, 09 Oct 2008) | 1 line update paragraph about __future__ for 2.6 ................ r66870 | armin.rigo | 2008-10-10 10:40:44 +0200 (Fri, 10 Oct 2008) | 2 lines Typo: "ThreadError" is the name in the C source. ................ r66871 | benjamin.peterson | 2008-10-10 22:38:49 +0200 (Fri, 10 Oct 2008) | 1 line fix a small typo ................ r66872 | benjamin.peterson | 2008-10-10 22:51:37 +0200 (Fri, 10 Oct 2008) | 1 line talk about how you can unzip with zip ................ r66874 | benjamin.peterson | 2008-10-11 00:23:41 +0200 (Sat, 11 Oct 2008) | 1 line PyGILState_Acquire -> PyGILState_Ensure ................ r66887 | benjamin.peterson | 2008-10-13 23:51:40 +0200 (Mon, 13 Oct 2008) | 1 line document how to disable fixers ................ r66903 | benjamin.peterson | 2008-10-15 22:34:09 +0200 (Wed, 15 Oct 2008) | 1 line don't recurse into directories that start with '.' ................ r66905 | benjamin.peterson | 2008-10-15 23:05:55 +0200 (Wed, 15 Oct 2008) | 1 line support the optional line argument for idle ................ r66911 | benjamin.peterson | 2008-10-16 01:10:28 +0200 (Thu, 16 Oct 2008) | 41 lines Merged revisions 66805,66841,66860,66884-66886,66893,66907,66910 via svnmerge from svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3 ........ r66805 | benjamin.peterson | 2008-10-04 20:11:02 -0500 (Sat, 04 Oct 2008) | 1 line mention what the fixes directory is for ........ r66841 | benjamin.peterson | 2008-10-07 17:48:12 -0500 (Tue, 07 Oct 2008) | 1 line use assertFalse and assertTrue ........ r66860 | benjamin.peterson | 2008-10-08 16:05:07 -0500 (Wed, 08 Oct 2008) | 1 line instead of abusing the pattern matcher, use start_tree to find a next binding ........ r66884 | benjamin.peterson | 2008-10-13 15:50:30 -0500 (Mon, 13 Oct 2008) | 1 line don't print tokens to stdout when -v is given ........ r66885 | benjamin.peterson | 2008-10-13 16:28:57 -0500 (Mon, 13 Oct 2008) | 1 line add the -x option to disable fixers ........ r66886 | benjamin.peterson | 2008-10-13 16:33:53 -0500 (Mon, 13 Oct 2008) | 1 line cut down on some crud ........ r66893 | benjamin.peterson | 2008-10-14 17:16:54 -0500 (Tue, 14 Oct 2008) | 1 line add an optional set literal fixer ........ r66907 | benjamin.peterson | 2008-10-15 16:59:41 -0500 (Wed, 15 Oct 2008) | 1 line don't write backup files by default ........ r66910 | benjamin.peterson | 2008-10-15 17:43:10 -0500 (Wed, 15 Oct 2008) | 1 line add the -n option; it stops backupfiles from being written ........ ................ r66913 | benjamin.peterson | 2008-10-16 20:52:14 +0200 (Thu, 16 Oct 2008) | 1 line document that deque indexing is O(n) #4123 ................ r66927 | andrew.kuchling | 2008-10-16 22:15:47 +0200 (Thu, 16 Oct 2008) | 1 line Fix wording (2.6.1 backport candidate) ................ r66932 | benjamin.peterson | 2008-10-16 23:09:28 +0200 (Thu, 16 Oct 2008) | 1 line check for error conditions in _json #3623 ................ r66938 | benjamin.peterson | 2008-10-16 23:27:54 +0200 (Thu, 16 Oct 2008) | 1 line fix possible ref leak ................ r66942 | benjamin.peterson | 2008-10-16 23:48:06 +0200 (Thu, 16 Oct 2008) | 1 line fix more possible ref leaks in _json and use Py_CLEAR ................ r66962 | benjamin.peterson | 2008-10-17 22:01:01 +0200 (Fri, 17 Oct 2008) | 1 line clarify CALL_FUNCTION #4141 ................ r66964 | georg.brandl | 2008-10-17 23:41:49 +0200 (Fri, 17 Oct 2008) | 2 lines Fix duplicate word. ................ r66973 | armin.ronacher | 2008-10-19 10:27:43 +0200 (Sun, 19 Oct 2008) | 3 lines Fixed #4067 by implementing _attributes and _fields for the AST root node. ................ r66974 | benjamin.peterson | 2008-10-19 15:59:01 +0200 (Sun, 19 Oct 2008) | 1 line fix compiler warning ................ r66977 | benjamin.peterson | 2008-10-19 21:39:16 +0200 (Sun, 19 Oct 2008) | 1 line mention -n ................ r66992 | benjamin.peterson | 2008-10-21 22:51:13 +0200 (Tue, 21 Oct 2008) | 1 line make sure to call iteritems() ................ r66998 | benjamin.peterson | 2008-10-22 22:57:43 +0200 (Wed, 22 Oct 2008) | 1 line fix a few typos ................ r66999 | benjamin.peterson | 2008-10-22 23:05:30 +0200 (Wed, 22 Oct 2008) | 1 line and another typo... ................ r67002 | hirokazu.yamamoto | 2008-10-23 02:37:33 +0200 (Thu, 23 Oct 2008) | 1 line Issue #4183: Some tests didn't run with pickle.HIGHEST_PROTOCOL. ................ r67005 | walter.doerwald | 2008-10-23 15:11:39 +0200 (Thu, 23 Oct 2008) | 2 lines Use the correct names of the stateless codec functions (Fixes issue 4178). ................ r67007 | benjamin.peterson | 2008-10-23 23:43:48 +0200 (Thu, 23 Oct 2008) | 1 line only nonempty __slots__ don't work ................ r67028 | benjamin.peterson | 2008-10-26 01:27:07 +0200 (Sun, 26 Oct 2008) | 1 line don't use a catch-all ................ r67040 | armin.rigo | 2008-10-28 18:01:21 +0100 (Tue, 28 Oct 2008) | 5 lines Fix one of the tests: it relied on being present in an "output test" in order to actually test what it was supposed to test, i.e. that the code in the __del__ method did not crash. Use instead the new helper test_support.captured_output(). ................ r67041 | benjamin.peterson | 2008-10-29 21:33:00 +0100 (Wed, 29 Oct 2008) | 1 line mention the version gettempdir() was added ................ r67044 | amaury.forgeotdarc | 2008-10-30 00:15:57 +0100 (Thu, 30 Oct 2008) | 3 lines Correct error message in io.open(): closefd=True is the only accepted value with a file name. ................ r67070 | benjamin.peterson | 2008-10-31 21:41:44 +0100 (Fri, 31 Oct 2008) | 1 line rephrase has_key doc ................ r67089 | benjamin.peterson | 2008-11-03 21:43:20 +0100 (Mon, 03 Nov 2008) | 1 line clarify by splitting into multiple paragraphs ................ r67091 | benjamin.peterson | 2008-11-03 23:34:57 +0100 (Mon, 03 Nov 2008) | 1 line move a FileIO test to test_fileio ................ r67101 | georg.brandl | 2008-11-04 21:49:35 +0100 (Tue, 04 Nov 2008) | 2 lines #4167: fix markup glitches. ................ r67117 | georg.brandl | 2008-11-06 11:17:58 +0100 (Thu, 06 Nov 2008) | 2 lines #4268: Use correct module for two toplevel functions. ................ r67118 | georg.brandl | 2008-11-06 11:19:11 +0100 (Thu, 06 Nov 2008) | 2 lines #4267: small fixes in sqlite3 docs. ................ r67119 | georg.brandl | 2008-11-06 11:20:49 +0100 (Thu, 06 Nov 2008) | 2 lines #4245: move Thread section to the top. ................ r67123 | georg.brandl | 2008-11-06 19:49:15 +0100 (Thu, 06 Nov 2008) | 2 lines #4247: add "pass" examples to tutorial. ................ r67124 | andrew.kuchling | 2008-11-06 20:23:02 +0100 (Thu, 06 Nov 2008) | 1 line Fix grammar error; reword two paragraphs ................
Diffstat (limited to 'Doc/whatsnew')
-rw-r--r--Doc/whatsnew/2.6.rst346
1 files changed, 173 insertions, 173 deletions
diff --git a/Doc/whatsnew/2.6.rst b/Doc/whatsnew/2.6.rst
index c7a3e20..96b254c 100644
--- a/Doc/whatsnew/2.6.rst
+++ b/Doc/whatsnew/2.6.rst
@@ -662,33 +662,33 @@ and :meth:`Semaphore` to create shared locks.)
from multiprocessing import Pool, Manager
def factorial(N, dictionary):
- "Compute a factorial."
- # Calculate the result
- fact = 1L
- for i in range(1, N+1):
- fact = fact * i
+ "Compute a factorial."
+ # Calculate the result
+ fact = 1L
+ for i in range(1, N+1):
+ fact = fact * i
# Store result in dictionary
- dictionary[N] = fact
+ dictionary[N] = fact
if __name__ == '__main__':
- p = Pool(5)
- mgr = Manager()
- d = mgr.dict() # Create shared dictionary
+ p = Pool(5)
+ mgr = Manager()
+ d = mgr.dict() # Create shared dictionary
- # Run tasks using the pool
- for N in range(1, 1000, 10):
- p.apply_async(factorial, (N, d))
+ # Run tasks using the pool
+ for N in range(1, 1000, 10):
+ p.apply_async(factorial, (N, d))
- # Mark pool as closed -- no more tasks can be added.
- p.close()
+ # Mark pool as closed -- no more tasks can be added.
+ p.close()
- # Wait for tasks to exit
- p.join()
+ # Wait for tasks to exit
+ p.join()
- # Output results
- for k, v in sorted(d.items()):
- print k, v
+ # Output results
+ for k, v in sorted(d.items()):
+ print k, v
This will produce the output::
@@ -723,32 +723,33 @@ In 2.6, both 8-bit and Unicode strings have a `.format()` method that
treats the string as a template and takes the arguments to be formatted.
The formatting template uses curly brackets (`{`, `}`) as special characters::
- # Substitute positional argument 0 into the string.
- "User ID: {0}".format("root") -> "User ID: root"
-
- # Use the named keyword arguments
- 'User ID: {uid} Last seen: {last_login}'.format(
- uid='root',
- last_login = '5 Mar 2008 07:20') ->
- 'User ID: root Last seen: 5 Mar 2008 07:20'
+ >>> # Substitute positional argument 0 into the string.
+ >>> "User ID: {0}".format("root")
+ 'User ID: root'
+ >>> # Use the named keyword arguments
+ >>> "User ID: {uid} Last seen: {last_login}".format(
+ ... uid="root",
+ ... last_login = "5 Mar 2008 07:20")
+ 'User ID: root Last seen: 5 Mar 2008 07:20'
Curly brackets can be escaped by doubling them::
- format("Empty dict: {{}}") -> "Empty dict: {}"
+ >>> format("Empty dict: {{}}")
+ "Empty dict: {}"
Field names can be integers indicating positional arguments, such as
``{0}``, ``{1}``, etc. or names of keyword arguments. You can also
supply compound field names that read attributes or access dictionary keys::
- import sys
- 'Platform: {0.platform}\nPython version: {0.version}'.format(sys) ->
- 'Platform: darwin\n
- Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41) \n
- [GCC 4.0.1 (Apple Computer, Inc. build 5367)]'
+ >>> import sys
+ >>> print 'Platform: {0.platform}\nPython version: {0.version}'.format(sys)
+ Platform: darwin
+ Python version: 2.6a1+ (trunk:61261M, Mar 5 2008, 20:29:41)
+ [GCC 4.0.1 (Apple Computer, Inc. build 5367)]'
- import mimetypes
- 'Content-type: {0[.mp4]}'.format(mimetypes.types_map) ->
- 'Content-type: video/mp4'
+ >>> import mimetypes
+ >>> 'Content-type: {0[.mp4]}'.format(mimetypes.types_map)
+ 'Content-type: video/mp4'
Note that when using dictionary-style notation such as ``[.mp4]``, you
don't need to put any quotation marks around the string; it will look
@@ -760,30 +761,25 @@ So far we've shown how to specify which field to substitute into the
resulting string. The precise formatting used is also controllable by
adding a colon followed by a format specifier. For example::
- # Field 0: left justify, pad to 15 characters
- # Field 1: right justify, pad to 6 characters
- fmt = '{0:15} ${1:>6}'
-
- fmt.format('Registration', 35) ->
- 'Registration $ 35'
-
- fmt.format('Tutorial', 50) ->
- 'Tutorial $ 50'
-
- fmt.format('Banquet', 125) ->
- 'Banquet $ 125'
+ >>> # Field 0: left justify, pad to 15 characters
+ >>> # Field 1: right justify, pad to 6 characters
+ >>> fmt = '{0:15} ${1:>6}'
+ >>> fmt.format('Registration', 35)
+ 'Registration $ 35'
+ >>> fmt.format('Tutorial', 50)
+ 'Tutorial $ 50'
+ >>> fmt.format('Banquet', 125)
+ 'Banquet $ 125'
Format specifiers can reference other fields through nesting::
- fmt = '{0:{1}}'
-
- width = 15
- fmt.format('Invoice #1234', width) ->
- 'Invoice #1234 '
-
- width = 35
- fmt.format('Invoice #1234', width) ->
- 'Invoice #1234 '
+ >>> fmt = '{0:{1}}'
+ >>> width = 15
+ >>> fmt.format('Invoice #1234', width)
+ 'Invoice #1234 '
+ >>> width = 35
+ >>> fmt.format('Invoice #1234', width)
+ 'Invoice #1234 '
The alignment of a field within the desired width can be specified:
@@ -798,7 +794,7 @@ Character Effect
Format specifiers can also include a presentation type, which
controls how the value is formatted. For example, floating-point numbers
-can be formatted as a general number or in exponential notation:
+can be formatted as a general number or in exponential notation::
>>> '{0:g}'.format(3.75)
'3.75'
@@ -806,25 +802,27 @@ can be formatted as a general number or in exponential notation:
'3.750000e+00'
A variety of presentation types are available. Consult the 2.6
-documentation for a :ref:`complete list <formatstrings>`; here's a sample::
-
- 'b' - Binary. Outputs the number in base 2.
- 'c' - Character. Converts the integer to the corresponding
- Unicode character before printing.
- 'd' - Decimal Integer. Outputs the number in base 10.
- 'o' - Octal format. Outputs the number in base 8.
- 'x' - Hex format. Outputs the number in base 16, using lower-
- case letters for the digits above 9.
- 'e' - Exponent notation. Prints the number in scientific
- notation using the letter 'e' to indicate the exponent.
- 'g' - General format. This prints the number as a fixed-point
- number, unless the number is too large, in which case
- it switches to 'e' exponent notation.
- 'n' - Number. This is the same as 'g' (for floats) or 'd' (for
- integers), except that it uses the current locale setting to
- insert the appropriate number separator characters.
- '%' - Percentage. Multiplies the number by 100 and displays
- in fixed ('f') format, followed by a percent sign.
+documentation for a :ref:`complete list <formatstrings>`; here's a sample:
+
+===== ========================================================================
+``b`` Binary. Outputs the number in base 2.
+``c`` Character. Converts the integer to the corresponding Unicode character
+ before printing.
+``d`` Decimal Integer. Outputs the number in base 10.
+``o`` Octal format. Outputs the number in base 8.
+``x`` Hex format. Outputs the number in base 16, using lower-case letters for
+ the digits above 9.
+``e`` Exponent notation. Prints the number in scientific notation using the
+ letter 'e' to indicate the exponent.
+``g`` General format. This prints the number as a fixed-point number, unless
+ the number is too large, in which case it switches to 'e' exponent
+ notation.
+``n`` Number. This is the same as 'g' (for floats) or 'd' (for integers),
+ except that it uses the current locale setting to insert the appropriate
+ number separator characters.
+``%`` Percentage. Multiplies the number by 100 and displays in fixed ('f')
+ format, followed by a percent sign.
+===== ========================================================================
Classes and types can define a :meth:`__format__` method to control how they're
formatted. It receives a single argument, the format specifier::
@@ -865,13 +863,14 @@ by doing ``def print(...)`` or importing a new function from somewhere else.
Python 2.6 has a ``__future__`` import that removes ``print`` as language
syntax, letting you use the functional form instead. For example::
- from __future__ import print_function
- print('# of entries', len(dictionary), file=sys.stderr)
+ >>> from __future__ import print_function
+ >>> print('# of entries', len(dictionary), file=sys.stderr)
The signature of the new function is::
def print(*args, sep=' ', end='\n', file=None)
+
The parameters are:
* *args*: positional arguments whose values will be printed out.
@@ -1002,6 +1001,8 @@ Byte arrays support most of the methods of string types, such as
and some of the methods of lists, such as :meth:`append`,
:meth:`pop`, and :meth:`reverse`.
+::
+
>>> b = bytearray('ABC')
>>> b.append('d')
>>> b.append(ord('e'))
@@ -1224,8 +1225,8 @@ To check whether an object supports a particular interface, you can
now write::
def func(d):
- if not isinstance(d, collections.MutableMapping):
- raise ValueError("Mapping object expected, not %r" % d)
+ if not isinstance(d, collections.MutableMapping):
+ raise ValueError("Mapping object expected, not %r" % d)
Don't feel that you must now begin writing lots of checks as in the
above example. Python has a strong tradition of duck-typing, where
@@ -1237,22 +1238,22 @@ do it where it's absolutely necessary.
You can write your own ABCs by using ``abc.ABCMeta`` as the
metaclass in a class definition::
- from abc import ABCMeta, abstractmethod
+ from abc import ABCMeta, abstractmethod
- class Drawable():
- __metaclass__ = ABCMeta
+ class Drawable():
+ __metaclass__ = ABCMeta
- @abstractmethod
- def draw(self, x, y, scale=1.0):
- pass
+ @abstractmethod
+ def draw(self, x, y, scale=1.0):
+ pass
- def draw_doubled(self, x, y):
- self.draw(x, y, scale=2.0)
+ def draw_doubled(self, x, y):
+ self.draw(x, y, scale=2.0)
- class Square(Drawable):
- def draw(self, x, y, scale):
- ...
+ class Square(Drawable):
+ def draw(self, x, y, scale):
+ ...
In the :class:`Drawable` ABC above, the :meth:`draw_doubled` method
@@ -1272,7 +1273,7 @@ try to create an instance of a subclass lacking the method::
>>> class Circle(Drawable):
... pass
...
- >>> c=Circle()
+ >>> c = Circle()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Circle with abstract methods draw
@@ -1331,7 +1332,7 @@ built-in returns the binary representation for a number::
The :func:`int` and :func:`long` built-ins will now accept the "0o"
and "0b" prefixes when base-8 or base-2 are requested, or when the
*base* argument is zero (signalling that the base used should be
-determined from the string):
+determined from the string)::
>>> int ('0o52', 0)
42
@@ -1504,7 +1505,7 @@ Some smaller changes made to the core Python language are:
(Contributed by Alexander Belopolsky; :issue:`1686487`.)
It's also become legal to provide keyword arguments after a ``*args`` argument
- to a function call.
+ to a function call. ::
>>> def f(*args, **kw):
... print args, kw
@@ -1545,17 +1546,17 @@ Some smaller changes made to the core Python language are:
property. You would use them like this::
class C(object):
- @property
- def x(self):
- return self._x
+ @property
+ def x(self):
+ return self._x
- @x.setter
- def x(self, value):
- self._x = value
+ @x.setter
+ def x(self, value):
+ self._x = value
- @x.deleter
- def x(self):
- del self._x
+ @x.deleter
+ def x(self):
+ del self._x
class D(C):
@C.x.getter
@@ -1878,8 +1879,8 @@ changes, or look through the Subversion logs for all the details.
>>> var_type = collections.namedtuple('variable',
... 'id name type size')
- # Names are separated by spaces or commas.
- # 'id, name, type, size' would also work.
+ >>> # Names are separated by spaces or commas.
+ >>> # 'id, name, type, size' would also work.
>>> var_type._fields
('id', 'name', 'type', 'size')
@@ -1929,11 +1930,13 @@ changes, or look through the Subversion logs for all the details.
* A new window method in the :mod:`curses` module,
:meth:`chgat`, changes the display attributes for a certain number of
- characters on a single line. (Contributed by Fabian Kreutz.) ::
+ characters on a single line. (Contributed by Fabian Kreutz.)
+
+ ::
# Boldface text starting at y=0,x=21
# and affecting the rest of the line.
- stdscr.chgat(0,21, curses.A_BOLD)
+ stdscr.chgat(0, 21, curses.A_BOLD)
The :class:`Textbox` class in the :mod:`curses.textpad` module
now supports editing in insert mode as well as overwrite mode.
@@ -1999,8 +2002,8 @@ changes, or look through the Subversion logs for all the details.
order, and returns a new generator that returns the contents of all
the iterators, also in sorted order. For example::
- heapq.merge([1, 3, 5, 9], [2, 8, 16]) ->
- [1, 2, 3, 5, 8, 9, 16]
+ >>> list(heapq.merge([1, 3, 5, 9], [2, 8, 16]))
+ [1, 2, 3, 5, 8, 9, 16]
Another new function, ``heappushpop(heap, item)``,
pushes *item* onto *heap*, then pops off and returns the smallest item.
@@ -2034,57 +2037,55 @@ changes, or look through the Subversion logs for all the details.
each of the elements; if some of the iterables are shorter than
others, the missing values are set to *fillvalue*. For example::
- itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
- (1, 1), (2, 2), (3, 3), (None, 4), (None, 5)
+ >>> tuple(itertools.izip_longest([1,2,3], [1,2,3,4,5]))
+ ((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))
``product(iter1, iter2, ..., [repeat=N])`` returns the Cartesian product
of the supplied iterables, a set of tuples containing
every possible combination of the elements returned from each iterable. ::
- itertools.product([1,2,3], [4,5,6]) ->
- (1, 4), (1, 5), (1, 6),
- (2, 4), (2, 5), (2, 6),
- (3, 4), (3, 5), (3, 6)
+ >>> list(itertools.product([1,2,3], [4,5,6]))
+ [(1, 4), (1, 5), (1, 6),
+ (2, 4), (2, 5), (2, 6),
+ (3, 4), (3, 5), (3, 6)]
The optional *repeat* keyword argument is used for taking the
product of an iterable or a set of iterables with themselves,
repeated *N* times. With a single iterable argument, *N*-tuples
are returned::
- itertools.product([1,2], repeat=3) ->
- (1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
- (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)
+ >>> list(itertools.product([1,2], repeat=3))
+ [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
+ (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
With two iterables, *2N*-tuples are returned. ::
- itertools.product([1,2], [3,4], repeat=2) ->
- (1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
- (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
- (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
- (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)
+ >>> list(itertools.product([1,2], [3,4], repeat=2))
+ [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
+ (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
+ (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
+ (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
``combinations(iterable, r)`` returns sub-sequences of length *r* from
the elements of *iterable*. ::
- itertools.combinations('123', 2) ->
- ('1', '2'), ('1', '3'), ('2', '3')
-
- itertools.combinations('123', 3) ->
- ('1', '2', '3')
-
- itertools.combinations('1234', 3) ->
- ('1', '2', '3'), ('1', '2', '4'), ('1', '3', '4'),
- ('2', '3', '4')
+ >>> list(itertools.combinations('123', 2))
+ [('1', '2'), ('1', '3'), ('2', '3')]
+ >>> list(itertools.combinations('123', 3))
+ [('1', '2', '3')]
+ >>> list(itertools.combinations('1234', 3))
+ [('1', '2', '3'), ('1', '2', '4'),
+ ('1', '3', '4'), ('2', '3', '4')]
``permutations(iter[, r])`` returns all the permutations of length *r* of
the iterable's elements. If *r* is not specified, it will default to the
number of elements produced by the iterable. ::
- itertools.permutations([1,2,3,4], 2) ->
- (1, 2), (1, 3), (1, 4),
- (2, 1), (2, 3), (2, 4),
- (3, 1), (3, 2), (3, 4),
- (4, 1), (4, 2), (4, 3)
+ >>> list(itertools.permutations([1,2,3,4], 2))
+ [(1, 2), (1, 3), (1, 4),
+ (2, 1), (2, 3), (2, 4),
+ (3, 1), (3, 2), (3, 4),
+ (4, 1), (4, 2), (4, 3)]
``itertools.chain(*iterables)`` is an existing function in
:mod:`itertools` that gained a new constructor in Python 2.6.
@@ -2093,8 +2094,8 @@ changes, or look through the Subversion logs for all the details.
then return all the elements of the first iterable, then
all the elements of the second, and so on. ::
- chain.from_iterable([[1,2,3], [4,5,6]]) ->
- 1, 2, 3, 4, 5, 6
+ >>> list(itertools.chain.from_iterable([[1,2,3], [4,5,6]]))
+ [1, 2, 3, 4, 5, 6]
(All contributed by Raymond Hettinger.)
@@ -2265,16 +2266,15 @@ changes, or look through the Subversion logs for all the details.
with an installed Python package. For example::
>>> import pkgutil
- >>> pkgutil.get_data('test', 'exception_hierarchy.txt')
- 'BaseException
+ >>> print pkgutil.get_data('test', 'exception_hierarchy.txt')
+ BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
- ...'
- >>>
+ ...
(Contributed by Paul Moore; :issue:`2439`.)
@@ -2548,9 +2548,9 @@ changes, or look through the Subversion logs for all the details.
with test_support.check_warnings() as wrec:
warnings.simplefilter("always")
- ... code that triggers a warning ...
+ # ... code that triggers a warning ...
assert str(wrec.message) == "function is outdated"
- assert len(wrec.warnings) == 1, "Multiple warnings raised"
+ assert len(wrec.warnings) == 1, "Multiple warnings raised"
(Contributed by Brett Cannon.)
@@ -2724,7 +2724,7 @@ for debugging::
t = ast.parse("""
d = {}
for i in 'abcdefghijklm':
- d[i + i] = ord(i) - ord('a') + 1
+ d[i + i] = ord(i) - ord('a') + 1
print d
""")
print ast.dump(t)
@@ -2733,32 +2733,32 @@ This outputs a deeply nested tree::
Module(body=[
Assign(targets=[
- Name(id='d', ctx=Store())
+ Name(id='d', ctx=Store())
], value=Dict(keys=[], values=[]))
For(target=Name(id='i', ctx=Store()),
- iter=Str(s='abcdefghijklm'), body=[
- Assign(targets=[
- Subscript(value=
- Name(id='d', ctx=Load()),
- slice=
- Index(value=
- BinOp(left=Name(id='i', ctx=Load()), op=Add(),
- right=Name(id='i', ctx=Load()))), ctx=Store())
- ], value=
- BinOp(left=
- BinOp(left=
- Call(func=
- Name(id='ord', ctx=Load()), args=[
- Name(id='i', ctx=Load())
- ], keywords=[], starargs=None, kwargs=None),
- op=Sub(), right=Call(func=
- Name(id='ord', ctx=Load()), args=[
- Str(s='a')
- ], keywords=[], starargs=None, kwargs=None)),
- op=Add(), right=Num(n=1)))
- ], orelse=[])
- Print(dest=None, values=[
- Name(id='d', ctx=Load())
+ iter=Str(s='abcdefghijklm'), body=[
+ Assign(targets=[
+ Subscript(value=
+ Name(id='d', ctx=Load()),
+ slice=
+ Index(value=
+ BinOp(left=Name(id='i', ctx=Load()), op=Add(),
+ right=Name(id='i', ctx=Load()))), ctx=Store())
+ ], value=
+ BinOp(left=
+ BinOp(left=
+ Call(func=
+ Name(id='ord', ctx=Load()), args=[
+ Name(id='i', ctx=Load())
+ ], keywords=[], starargs=None, kwargs=None),
+ op=Sub(), right=Call(func=
+ Name(id='ord', ctx=Load()), args=[
+ Str(s='a')
+ ], keywords=[], starargs=None, kwargs=None)),
+ op=Add(), right=Num(n=1)))
+ ], orelse=[])
+ Print(dest=None, values=[
+ Name(id='d', ctx=Load())
], nl=True)
])
@@ -2862,8 +2862,8 @@ Using the module is simple::
# Create data structure
data_struct = dict(lastAccessed=datetime.datetime.now(),
- version=1,
- categories=('Personal','Shared','Private'))
+ version=1,
+ categories=('Personal','Shared','Private'))
# Create string containing XML.
plist_str = plistlib.writePlistToString(data_struct)