Kaydet (Commit) e8f1b003 authored tarafından Georg Brandl's avatar Georg Brandl

Enable doctest running for several other documents.

We have now over 640 doctests that are run with "make doctest".
üst 7a45ab82
...@@ -150,7 +150,7 @@ The legacy interface: ...@@ -150,7 +150,7 @@ The legacy interface:
:func:`encodestring` returns a string containing one or more lines of :func:`encodestring` returns a string containing one or more lines of
base64-encoded data always including an extra trailing newline (``'\n'``). base64-encoded data always including an extra trailing newline (``'\n'``).
An example usage of the module:: An example usage of the module:
>>> import base64 >>> import base64
>>> encoded = base64.b64encode('data to be encoded') >>> encoded = base64.b64encode('data to be encoded')
......
...@@ -72,7 +72,7 @@ Examples ...@@ -72,7 +72,7 @@ Examples
The :func:`bisect` function is generally useful for categorizing numeric data. The :func:`bisect` function is generally useful for categorizing numeric data.
This example uses :func:`bisect` to look up a letter grade for an exam total This example uses :func:`bisect` to look up a letter grade for an exam total
(say) based on a set of ordered numeric breakpoints: 85 and up is an 'A', 75..84 (say) based on a set of ordered numeric breakpoints: 85 and up is an 'A', 75..84
is a 'B', etc. :: is a 'B', etc.
>>> grades = "FEDCBA" >>> grades = "FEDCBA"
>>> breakpoints = [30, 44, 66, 75, 85] >>> breakpoints = [30, 44, 66, 75, 85]
......
...@@ -210,7 +210,10 @@ Morsel Objects ...@@ -210,7 +210,10 @@ Morsel Objects
Example Example
------- -------
The following example demonstrates how to use the :mod:`Cookie` module. :: The following example demonstrates how to use the :mod:`Cookie` module.
.. doctest::
:options: +NORMALIZE_WHITESPACE
>>> import Cookie >>> import Cookie
>>> C = Cookie.SimpleCookie() >>> C = Cookie.SimpleCookie()
...@@ -219,11 +222,11 @@ The following example demonstrates how to use the :mod:`Cookie` module. :: ...@@ -219,11 +222,11 @@ The following example demonstrates how to use the :mod:`Cookie` module. ::
>>> C["fig"] = "newton" >>> C["fig"] = "newton"
>>> C["sugar"] = "wafer" >>> C["sugar"] = "wafer"
>>> print C # generate HTTP headers >>> print C # generate HTTP headers
Set-Cookie: sugar=wafer
Set-Cookie: fig=newton Set-Cookie: fig=newton
>>> print C.output() # same thing
Set-Cookie: sugar=wafer Set-Cookie: sugar=wafer
>>> print C.output() # same thing
Set-Cookie: fig=newton Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
>>> C["rocky"] = "road" >>> C["rocky"] = "road"
>>> C["rocky"]["path"] = "/cookie" >>> C["rocky"]["path"] = "/cookie"
...@@ -234,8 +237,8 @@ The following example demonstrates how to use the :mod:`Cookie` module. :: ...@@ -234,8 +237,8 @@ The following example demonstrates how to use the :mod:`Cookie` module. ::
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
>>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header) >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
>>> print C >>> print C
Set-Cookie: vienna=finger
Set-Cookie: chips=ahoy Set-Cookie: chips=ahoy
Set-Cookie: vienna=finger
>>> C = Cookie.SmartCookie() >>> C = Cookie.SmartCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
>>> print C >>> print C
......
:mod:`difflib` --- Helpers for computing deltas :mod:`difflib` --- Helpers for computing deltas
=============================================== ===============================================
...@@ -8,7 +7,10 @@ ...@@ -8,7 +7,10 @@
.. sectionauthor:: Tim Peters <tim_one@users.sourceforge.net> .. sectionauthor:: Tim Peters <tim_one@users.sourceforge.net>
.. Markup by Fred L. Drake, Jr. <fdrake@acm.org> .. Markup by Fred L. Drake, Jr. <fdrake@acm.org>
.. testsetup::
import sys
from difflib import *
.. versionadded:: 2.1 .. versionadded:: 2.1
...@@ -148,12 +150,10 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module. ...@@ -148,12 +150,10 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
expressed in the format returned by :func:`time.ctime`. If not specified, the expressed in the format returned by :func:`time.ctime`. If not specified, the
strings default to blanks. strings default to blanks.
::
>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
>>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
>>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'): >>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'):
... sys.stdout.write(line) ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE
*** before.py *** before.py
--- after.py --- after.py
*************** ***************
...@@ -186,7 +186,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module. ...@@ -186,7 +186,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
Possibilities that don't score at least that similar to *word* are ignored. Possibilities that don't score at least that similar to *word* are ignored.
The best (no more than *n*) matches among the possibilities are returned in a The best (no more than *n*) matches among the possibilities are returned in a
list, sorted by similarity score, most similar first. :: list, sorted by similarity score, most similar first.
>>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
['apple', 'ape'] ['apple', 'ape']
...@@ -221,7 +221,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module. ...@@ -221,7 +221,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a
blank or tab; note: bad idea to include newline in this!). blank or tab; note: bad idea to include newline in this!).
:file:`Tools/scripts/ndiff.py` is a command-line front-end to this function. :: :file:`Tools/scripts/ndiff.py` is a command-line front-end to this function.
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1)) ... 'ore\ntree\nemu\n'.splitlines(1))
...@@ -245,7 +245,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module. ...@@ -245,7 +245,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
lines originating from file 1 or 2 (parameter *which*), stripping off line lines originating from file 1 or 2 (parameter *which*), stripping off line
prefixes. prefixes.
Example:: Example:
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1)) ... 'ore\ntree\nemu\n'.splitlines(1))
...@@ -285,13 +285,10 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module. ...@@ -285,13 +285,10 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
expressed in the format returned by :func:`time.ctime`. If not specified, the expressed in the format returned by :func:`time.ctime`. If not specified, the
strings default to blanks. strings default to blanks.
::
>>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
>>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
>>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'): >>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'):
... sys.stdout.write(line) ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE
--- before.py --- before.py
+++ after.py +++ after.py
@@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
...@@ -388,11 +385,11 @@ use :meth:`set_seq2` to set the commonly used sequence once and call ...@@ -388,11 +385,11 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
conditions, the additional conditions ``k >= k'``, ``i <= i'``, and if ``i == conditions, the additional conditions ``k >= k'``, ``i <= i'``, and if ``i ==
i'``, ``j <= j'`` are also met. In other words, of all maximal matching blocks, i'``, ``j <= j'`` are also met. In other words, of all maximal matching blocks,
return one that starts earliest in *a*, and of all those maximal matching blocks return one that starts earliest in *a*, and of all those maximal matching blocks
that start earliest in *a*, return the one that starts earliest in *b*. :: that start earliest in *a*, return the one that starts earliest in *b*.
>>> s = SequenceMatcher(None, " abcd", "abcd abcd") >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9) >>> s.find_longest_match(0, 5, 0, 9)
(0, 4, 5) Match(a=0, b=4, size=5)
If *isjunk* was provided, first the longest matching block is determined as If *isjunk* was provided, first the longest matching block is determined as
above, but with the additional restriction that no junk element appears in the above, but with the additional restriction that no junk element appears in the
...@@ -403,11 +400,11 @@ use :meth:`set_seq2` to set the commonly used sequence once and call ...@@ -403,11 +400,11 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
Here's the same example as before, but considering blanks to be junk. That Here's the same example as before, but considering blanks to be junk. That
prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the second prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the second
sequence directly. Instead only the ``'abcd'`` can match, and matches the sequence directly. Instead only the ``'abcd'`` can match, and matches the
leftmost ``'abcd'`` in the second sequence:: leftmost ``'abcd'`` in the second sequence:
>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9) >>> s.find_longest_match(0, 5, 0, 9)
(1, 0, 4) Match(a=1, b=0, size=4)
If no blocks match, this returns ``(alo, blo, 0)``. If no blocks match, this returns ``(alo, blo, 0)``.
...@@ -433,11 +430,11 @@ use :meth:`set_seq2` to set the commonly used sequence once and call ...@@ -433,11 +430,11 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
The guarantee that adjacent triples always describe non-adjacent blocks was The guarantee that adjacent triples always describe non-adjacent blocks was
implemented. implemented.
:: .. doctest::
>>> s = SequenceMatcher(None, "abxcd", "abcd") >>> s = SequenceMatcher(None, "abxcd", "abcd")
>>> s.get_matching_blocks() >>> s.get_matching_blocks()
[(0, 0, 2), (3, 2, 2), (5, 4, 0)] [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
.. method:: SequenceMatcher.get_opcodes() .. method:: SequenceMatcher.get_opcodes()
...@@ -466,7 +463,7 @@ use :meth:`set_seq2` to set the commonly used sequence once and call ...@@ -466,7 +463,7 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
| | are equal). | | | are equal). |
+---------------+---------------------------------------------+ +---------------+---------------------------------------------+
For example:: For example:
>>> a = "qabxcd" >>> a = "qabxcd"
>>> b = "abycdf" >>> b = "abycdf"
...@@ -524,7 +521,7 @@ use :meth:`set_seq2` to set the commonly used sequence once and call ...@@ -524,7 +521,7 @@ use :meth:`set_seq2` to set the commonly used sequence once and call
The three methods that return the ratio of matching to total characters can give The three methods that return the ratio of matching to total characters can give
different results due to differing levels of approximation, although different results due to differing levels of approximation, although
:meth:`quick_ratio` and :meth:`real_quick_ratio` are always at least as large as :meth:`quick_ratio` and :meth:`real_quick_ratio` are always at least as large as
:meth:`ratio`:: :meth:`ratio`:
>>> s = SequenceMatcher(None, "abcd", "bcde") >>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio() >>> s.ratio()
...@@ -540,7 +537,7 @@ different results due to differing levels of approximation, although ...@@ -540,7 +537,7 @@ different results due to differing levels of approximation, although
SequenceMatcher Examples SequenceMatcher Examples
------------------------ ------------------------
This example compares two strings, considering blanks to be "junk:" :: This example compares two strings, considering blanks to be "junk:"
>>> s = SequenceMatcher(lambda x: x == " ", >>> s = SequenceMatcher(lambda x: x == " ",
... "private Thread currentThread;", ... "private Thread currentThread;",
...@@ -548,19 +545,18 @@ This example compares two strings, considering blanks to be "junk:" :: ...@@ -548,19 +545,18 @@ This example compares two strings, considering blanks to be "junk:" ::
:meth:`ratio` returns a float in [0, 1], measuring the similarity of the :meth:`ratio` returns a float in [0, 1], measuring the similarity of the
sequences. As a rule of thumb, a :meth:`ratio` value over 0.6 means the sequences. As a rule of thumb, a :meth:`ratio` value over 0.6 means the
sequences are close matches:: sequences are close matches:
>>> print round(s.ratio(), 3) >>> print round(s.ratio(), 3)
0.866 0.866
If you're only interested in where the sequences match, If you're only interested in where the sequences match,
:meth:`get_matching_blocks` is handy:: :meth:`get_matching_blocks` is handy:
>>> for block in s.get_matching_blocks(): >>> for block in s.get_matching_blocks():
... print "a[%d] and b[%d] match for %d elements" % block ... print "a[%d] and b[%d] match for %d elements" % block
a[0] and b[0] match for 8 elements a[0] and b[0] match for 8 elements
a[8] and b[17] match for 6 elements a[8] and b[17] match for 21 elements
a[14] and b[23] match for 15 elements
a[29] and b[38] match for 0 elements a[29] and b[38] match for 0 elements
Note that the last tuple returned by :meth:`get_matching_blocks` is always a Note that the last tuple returned by :meth:`get_matching_blocks` is always a
...@@ -568,14 +564,13 @@ dummy, ``(len(a), len(b), 0)``, and this is the only case in which the last ...@@ -568,14 +564,13 @@ dummy, ``(len(a), len(b), 0)``, and this is the only case in which the last
tuple element (number of elements matched) is ``0``. tuple element (number of elements matched) is ``0``.
If you want to know how to change the first sequence into the second, use If you want to know how to change the first sequence into the second, use
:meth:`get_opcodes`:: :meth:`get_opcodes`:
>>> for opcode in s.get_opcodes(): >>> for opcode in s.get_opcodes():
... print "%6s a[%d:%d] b[%d:%d]" % opcode ... print "%6s a[%d:%d] b[%d:%d]" % opcode
equal a[0:8] b[0:8] equal a[0:8] b[0:8]
insert a[8:8] b[8:17] insert a[8:8] b[8:17]
equal a[8:14] b[17:23] equal a[8:29] b[17:38]
equal a[14:29] b[23:38]
See also the function :func:`get_close_matches` in this module, which shows how See also the function :func:`get_close_matches` in this module, which shows how
simple code building on :class:`SequenceMatcher` can be used to do useful work. simple code building on :class:`SequenceMatcher` can be used to do useful work.
...@@ -628,7 +623,7 @@ Differ Example ...@@ -628,7 +623,7 @@ Differ Example
This example compares two texts. First we set up the texts, sequences of This example compares two texts. First we set up the texts, sequences of
individual single-line strings ending with newlines (such sequences can also be individual single-line strings ending with newlines (such sequences can also be
obtained from the :meth:`readlines` method of file-like objects):: obtained from the :meth:`readlines` method of file-like objects):
>>> text1 = ''' 1. Beautiful is better than ugly. >>> text1 = ''' 1. Beautiful is better than ugly.
... 2. Explicit is better than implicit. ... 2. Explicit is better than implicit.
...@@ -645,7 +640,7 @@ obtained from the :meth:`readlines` method of file-like objects):: ...@@ -645,7 +640,7 @@ obtained from the :meth:`readlines` method of file-like objects)::
... 5. Flat is better than nested. ... 5. Flat is better than nested.
... '''.splitlines(1) ... '''.splitlines(1)
Next we instantiate a Differ object:: Next we instantiate a Differ object:
>>> d = Differ() >>> d = Differ()
...@@ -653,11 +648,11 @@ Note that when instantiating a :class:`Differ` object we may pass functions to ...@@ -653,11 +648,11 @@ Note that when instantiating a :class:`Differ` object we may pass functions to
filter out line and character "junk." See the :meth:`Differ` constructor for filter out line and character "junk." See the :meth:`Differ` constructor for
details. details.
Finally, we compare the two:: Finally, we compare the two:
>>> result = list(d.compare(text1, text2)) >>> result = list(d.compare(text1, text2))
``result`` is a list of strings, so let's pretty-print it:: ``result`` is a list of strings, so let's pretty-print it:
>>> from pprint import pprint >>> from pprint import pprint
>>> pprint(result) >>> pprint(result)
...@@ -665,14 +660,14 @@ Finally, we compare the two:: ...@@ -665,14 +660,14 @@ Finally, we compare the two::
'- 2. Explicit is better than implicit.\n', '- 2. Explicit is better than implicit.\n',
'- 3. Simple is better than complex.\n', '- 3. Simple is better than complex.\n',
'+ 3. Simple is better than complex.\n', '+ 3. Simple is better than complex.\n',
'? ++ \n', '? ++\n',
'- 4. Complex is better than complicated.\n', '- 4. Complex is better than complicated.\n',
'? ^ ---- ^ \n', '? ^ ---- ^\n',
'+ 4. Complicated is better than complex.\n', '+ 4. Complicated is better than complex.\n',
'? ++++ ^ ^ \n', '? ++++ ^ ^\n',
'+ 5. Flat is better than nested.\n'] '+ 5. Flat is better than nested.\n']
As a single multi-line string it looks like this:: As a single multi-line string it looks like this:
>>> import sys >>> import sys
>>> sys.stdout.writelines(result) >>> sys.stdout.writelines(result)
...@@ -697,7 +692,7 @@ This example shows how to use difflib to create a ``diff``-like utility. ...@@ -697,7 +692,7 @@ This example shows how to use difflib to create a ``diff``-like utility.
It is also contained in the Python source distribution, as It is also contained in the Python source distribution, as
:file:`Tools/scripts/diff.py`. :file:`Tools/scripts/diff.py`.
:: .. testcode::
""" Command line interface to difflib.py providing diffs in four formats: """ Command line interface to difflib.py providing diffs in four formats:
......
...@@ -72,7 +72,7 @@ patterns. ...@@ -72,7 +72,7 @@ patterns.
Return the shell-style *pattern* converted to a regular expression. Return the shell-style *pattern* converted to a regular expression.
Example:: Example:
>>> import fnmatch, re >>> import fnmatch, re
>>> >>>
......
...@@ -50,18 +50,19 @@ Fraction number class. ...@@ -50,18 +50,19 @@ Fraction number class.
Finds and returns the closest :class:`Fraction` to ``self`` that Finds and returns the closest :class:`Fraction` to ``self`` that
has denominator at most max_denominator. This method is useful for has denominator at most max_denominator. This method is useful for
finding rational approximations to a given floating-point number:: finding rational approximations to a given floating-point number:
>>> from fractions import Fraction
>>> Fraction('3.1415926535897932').limit_denominator(1000) >>> Fraction('3.1415926535897932').limit_denominator(1000)
Fraction(355, 113) Fraction(355L, 113L)
or for recovering a rational number that's represented as a float:: or for recovering a rational number that's represented as a float:
>>> from math import pi, cos >>> from math import pi, cos
>>> Fraction.from_float(cos(pi/3)) >>> Fraction.from_float(cos(pi/3))
Fraction(4503599627370497L, 9007199254740992L) Fraction(4503599627370497L, 9007199254740992L)
>>> Fraction.from_float(cos(pi/3)).limit_denominator() >>> Fraction.from_float(cos(pi/3)).limit_denominator()
Fraction(1, 2) Fraction(1L, 2L)
.. method:: Fraction.__floor__() .. method:: Fraction.__floor__()
...@@ -90,4 +91,3 @@ Fraction number class. ...@@ -90,4 +91,3 @@ Fraction number class.
Module :mod:`numbers` Module :mod:`numbers`
The abstract base classes making up the numeric tower. The abstract base classes making up the numeric tower.
...@@ -48,8 +48,9 @@ The :mod:`functools` module defines the following functions: ...@@ -48,8 +48,9 @@ The :mod:`functools` module defines the following functions:
some portion of a function's arguments and/or keywords resulting in a new object some portion of a function's arguments and/or keywords resulting in a new object
with a simplified signature. For example, :func:`partial` can be used to create with a simplified signature. For example, :func:`partial` can be used to create
a callable that behaves like the :func:`int` function where the *base* argument a callable that behaves like the :func:`int` function where the *base* argument
defaults to two:: defaults to two:
>>> from functools import partial
>>> basetwo = partial(int, base=2) >>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.' >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010') >>> basetwo('10010')
...@@ -79,8 +80,9 @@ The :mod:`functools` module defines the following functions: ...@@ -79,8 +80,9 @@ The :mod:`functools` module defines the following functions:
This is a convenience function for invoking ``partial(update_wrapper, This is a convenience function for invoking ``partial(update_wrapper,
wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
when defining a wrapper function. For example:: when defining a wrapper function. For example:
>>> from functools import wraps
>>> def my_decorator(f): >>> def my_decorator(f):
... @wraps(f) ... @wraps(f)
... def wrapper(*args, **kwds): ... def wrapper(*args, **kwds):
......
...@@ -82,7 +82,7 @@ exception: ...@@ -82,7 +82,7 @@ exception:
Alias for :exc:`GetoptError`; for backward compatibility. Alias for :exc:`GetoptError`; for backward compatibility.
An example using only Unix style options:: An example using only Unix style options:
>>> import getopt >>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split() >>> args = '-a -b -cfoo -d bar a1 a2'.split()
...@@ -94,7 +94,7 @@ An example using only Unix style options:: ...@@ -94,7 +94,7 @@ An example using only Unix style options::
>>> args >>> args
['a1', 'a2'] ['a1', 'a2']
Using long option names is equally easy:: Using long option names is equally easy:
>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2' >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split() >>> args = s.split()
...@@ -103,8 +103,7 @@ Using long option names is equally easy:: ...@@ -103,8 +103,7 @@ Using long option names is equally easy::
>>> optlist, args = getopt.getopt(args, 'x', [ >>> optlist, args = getopt.getopt(args, 'x', [
... 'condition=', 'output-file=', 'testing']) ... 'condition=', 'output-file=', 'testing'])
>>> optlist >>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
'')]
>>> args >>> args
['a1', 'a2'] ['a1', 'a2']
......
...@@ -44,7 +44,7 @@ Constructors for hash algorithms that are always present in this module are ...@@ -44,7 +44,7 @@ Constructors for hash algorithms that are always present in this module are
OpenSSL library that Python uses on your platform. OpenSSL library that Python uses on your platform.
For example, to obtain the digest of the string ``'Nobody inspects the spammish For example, to obtain the digest of the string ``'Nobody inspects the spammish
repetition'``:: repetition'``:
>>> import hashlib >>> import hashlib
>>> m = hashlib.md5() >>> m = hashlib.md5()
...@@ -57,7 +57,7 @@ repetition'``:: ...@@ -57,7 +57,7 @@ repetition'``::
>>> m.block_size >>> m.block_size
64 64
More condensed:: More condensed:
>>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest() >>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest()
'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
...@@ -67,7 +67,7 @@ algorithm as its first parameter also exists to allow access to the above listed ...@@ -67,7 +67,7 @@ algorithm as its first parameter also exists to allow access to the above listed
hashes as well as any other algorithms that your OpenSSL library may offer. The hashes as well as any other algorithms that your OpenSSL library may offer. The
named constructors are much faster than :func:`new` and should be preferred. named constructors are much faster than :func:`new` and should be preferred.
Using :func:`new` with an algorithm provided by OpenSSL:: Using :func:`new` with an algorithm provided by OpenSSL:
>>> h = hashlib.new('ripemd160') >>> h = hashlib.new('ripemd160')
>>> h.update("Nobody inspects the spammish repetition") >>> h.update("Nobody inspects the spammish repetition")
......
...@@ -70,7 +70,7 @@ The following functions are provided: ...@@ -70,7 +70,7 @@ The following functions are provided:
if item > heap[0]: if item > heap[0]:
item = heapreplace(heap, item) item = heapreplace(heap, item)
Example of use:: Example of use:
>>> from heapq import heappush, heappop >>> from heapq import heappush, heappop
>>> heap = [] >>> heap = []
...@@ -87,7 +87,6 @@ Example of use:: ...@@ -87,7 +87,6 @@ Example of use::
>>> data.sort() >>> data.sort()
>>> print data == ordered >>> print data == ordered
True True
>>>
The module also offers three general purpose functions based on heaps. The module also offers three general purpose functions based on heaps.
......
...@@ -8,6 +8,10 @@ ...@@ -8,6 +8,10 @@
.. sectionauthor:: Raymond Hettinger <python@rcn.com> .. sectionauthor:: Raymond Hettinger <python@rcn.com>
.. testsetup::
from itertools import *
.. versionadded:: 2.3 .. versionadded:: 2.3
This module implements a number of :term:`iterator` building blocks inspired by This module implements a number of :term:`iterator` building blocks inspired by
...@@ -549,7 +553,9 @@ Examples ...@@ -549,7 +553,9 @@ Examples
-------- --------
The following examples show common uses for each tool and demonstrate ways they The following examples show common uses for each tool and demonstrate ways they
can be combined. :: can be combined.
.. doctest::
# Show a dictionary sorted and grouped by value # Show a dictionary sorted and grouped by value
>>> from operator import itemgetter >>> from operator import itemgetter
...@@ -567,7 +573,7 @@ can be combined. :: ...@@ -567,7 +573,7 @@ can be combined. ::
# same group. # same group.
>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
>>> for k, g in groupby(enumerate(data), lambda (i,x):i-x): >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
... print map(operator.itemgetter(1), g) ... print map(itemgetter(1), g)
... ...
[1] [1]
[4, 5, 6] [4, 5, 6]
...@@ -592,7 +598,9 @@ rather than bringing the whole iterable into memory all at once. Code volume is ...@@ -592,7 +598,9 @@ rather than bringing the whole iterable into memory all at once. Code volume is
kept small by linking the tools together in a functional style which helps kept small by linking the tools together in a functional style which helps
eliminate temporary variables. High speed is retained by preferring eliminate temporary variables. High speed is retained by preferring
"vectorized" building blocks over the use of for-loops and :term:`generator`\s "vectorized" building blocks over the use of for-loops and :term:`generator`\s
which incur interpreter overhead. :: which incur interpreter overhead.
.. testcode::
def take(n, seq): def take(n, seq):
return list(islice(seq, n)) return list(islice(seq, n))
......
...@@ -22,7 +22,7 @@ using the :meth:`update` method, and at any point you can ask it for the ...@@ -22,7 +22,7 @@ using the :meth:`update` method, and at any point you can ask it for the
concatenation of the strings fed to it so far using the :meth:`digest` method. concatenation of the strings fed to it so far using the :meth:`digest` method.
For example, to obtain the digest of the string ``'Nobody inspects the spammish For example, to obtain the digest of the string ``'Nobody inspects the spammish
repetition'``:: repetition'``:
>>> import md5 >>> import md5
>>> m = md5.new() >>> m = md5.new()
...@@ -31,7 +31,7 @@ repetition'``:: ...@@ -31,7 +31,7 @@ repetition'``::
>>> m.digest() >>> m.digest()
'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9' '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
More condensed:: More condensed:
>>> md5.new("Nobody inspects the spammish repetition").digest() >>> md5.new("Nobody inspects the spammish repetition").digest()
'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9' '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
......
...@@ -25,7 +25,7 @@ scheduler: ...@@ -25,7 +25,7 @@ scheduler:
Example:: Example::
>>> import sched, time >>> import sched, time
>>> s=sched.scheduler(time.time, time.sleep) >>> s = sched.scheduler(time.time, time.sleep)
>>> def print_time(): print "From print_time", time.time() >>> def print_time(): print "From print_time", time.time()
... ...
>>> def print_some_times(): >>> def print_some_times():
......
...@@ -192,8 +192,6 @@ the builtin :class:`set()` and :class:`frozenset()` types. ...@@ -192,8 +192,6 @@ the builtin :class:`set()` and :class:`frozenset()` types.
Example Example
------- -------
::
>>> from sets import Set >>> from sets import Set
>>> engineers = Set(['John', 'Jane', 'Jack', 'Janice']) >>> engineers = Set(['John', 'Jane', 'Jack', 'Janice'])
>>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice']) >>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
...@@ -202,14 +200,14 @@ Example ...@@ -202,14 +200,14 @@ Example
>>> engineering_management = engineers & managers # intersection >>> engineering_management = engineers & managers # intersection
>>> fulltime_management = managers - engineers - programmers # difference >>> fulltime_management = managers - engineers - programmers # difference
>>> engineers.add('Marvin') # add element >>> engineers.add('Marvin') # add element
>>> print engineers >>> print engineers # doctest: +SKIP
Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack']) Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
>>> employees.issuperset(engineers) # superset test >>> employees.issuperset(engineers) # superset test
False False
>>> employees.update(engineers) # update from another set >>> employees.update(engineers) # update from another set
>>> employees.issuperset(engineers) >>> employees.issuperset(engineers)
True True
>>> for group in [engineers, programmers, managers, employees]: >>> for group in [engineers, programmers, managers, employees]: # doctest: +SKIP
... group.discard('Susan') # unconditionally remove element ... group.discard('Susan') # unconditionally remove element
... print group ... print group
... ...
......
...@@ -630,7 +630,7 @@ Notes: ...@@ -630,7 +630,7 @@ Notes:
Values of *n* less than ``0`` are treated as ``0`` (which yields an empty Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
sequence of the same type as *s*). Note also that the copies are shallow; sequence of the same type as *s*). Note also that the copies are shallow;
nested structures are not copied. This often haunts new Python programmers; nested structures are not copied. This often haunts new Python programmers;
consider:: consider:
>>> lists = [[]] * 3 >>> lists = [[]] * 3
>>> lists >>> lists
...@@ -642,7 +642,7 @@ Notes: ...@@ -642,7 +642,7 @@ Notes:
What has happened is that ``[[]]`` is a one-element list containing an empty What has happened is that ``[[]]`` is a one-element list containing an empty
list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
list. Modifying any of the elements of ``lists`` modifies this single list. list. Modifying any of the elements of ``lists`` modifies this single list.
You can create a list of different lists this way:: You can create a list of different lists this way:
>>> lists = [[] for i in range(3)] >>> lists = [[] for i in range(3)]
>>> lists[0].append(3) >>> lists[0].append(3)
...@@ -875,7 +875,7 @@ string functions based on regular expressions. ...@@ -875,7 +875,7 @@ string functions based on regular expressions.
Return a copy of the string with leading characters removed. The *chars* Return a copy of the string with leading characters removed. The *chars*
argument is a string specifying the set of characters to be removed. If omitted argument is a string specifying the set of characters to be removed. If omitted
or ``None``, the *chars* argument defaults to removing whitespace. The *chars* or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
argument is not a prefix; rather, all combinations of its values are stripped:: argument is not a prefix; rather, all combinations of its values are stripped:
>>> ' spacious '.lstrip() >>> ' spacious '.lstrip()
'spacious ' 'spacious '
...@@ -952,7 +952,7 @@ string functions based on regular expressions. ...@@ -952,7 +952,7 @@ string functions based on regular expressions.
Return a copy of the string with trailing characters removed. The *chars* Return a copy of the string with trailing characters removed. The *chars*
argument is a string specifying the set of characters to be removed. If omitted argument is a string specifying the set of characters to be removed. If omitted
or ``None``, the *chars* argument defaults to removing whitespace. The *chars* or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
argument is not a suffix; rather, all combinations of its values are stripped:: argument is not a suffix; rather, all combinations of its values are stripped:
>>> ' spacious '.rstrip() >>> ' spacious '.rstrip()
' spacious' ' spacious'
...@@ -1012,7 +1012,7 @@ string functions based on regular expressions. ...@@ -1012,7 +1012,7 @@ string functions based on regular expressions.
The *chars* argument is a string specifying the set of characters to be removed. The *chars* argument is a string specifying the set of characters to be removed.
If omitted or ``None``, the *chars* argument defaults to removing whitespace. If omitted or ``None``, the *chars* argument defaults to removing whitespace.
The *chars* argument is not a prefix or suffix; rather, all combinations of its The *chars* argument is not a prefix or suffix; rather, all combinations of its
values are stripped:: values are stripped:
>>> ' spacious '.strip() >>> ' spacious '.strip()
'spacious' 'spacious'
...@@ -1048,7 +1048,7 @@ string functions based on regular expressions. ...@@ -1048,7 +1048,7 @@ string functions based on regular expressions.
You can use the :func:`maketrans` helper function in the :mod:`string` module to You can use the :func:`maketrans` helper function in the :mod:`string` module to
create a translation table. For string objects, set the *table* argument to create a translation table. For string objects, set the *table* argument to
``None`` for translations that only delete characters:: ``None`` for translations that only delete characters:
>>> 'read this short text'.translate(None, 'aeiou') >>> 'read this short text'.translate(None, 'aeiou')
'rd ths shrt txt' 'rd ths shrt txt'
...@@ -1155,10 +1155,10 @@ components, which must occur in this order: ...@@ -1155,10 +1155,10 @@ components, which must occur in this order:
When the right argument is a dictionary (or other mapping type), then the When the right argument is a dictionary (or other mapping type), then the
formats in the string *must* include a parenthesised mapping key into that formats in the string *must* include a parenthesised mapping key into that
dictionary inserted immediately after the ``'%'`` character. The mapping key dictionary inserted immediately after the ``'%'`` character. The mapping key
selects the value to be formatted from the mapping. For example:: selects the value to be formatted from the mapping. For example:
>>> print '%(language)s has %(#)03d quote types.' % \ >>> print '%(language)s has %(#)03d quote types.' % \
{'language': "Python", "#": 2} ... {'language': "Python", "#": 2}
Python has 002 quote types. Python has 002 quote types.
In this case no ``*`` specifiers may occur in a format (since they require a In this case no ``*`` specifiers may occur in a format (since they require a
......
...@@ -168,7 +168,7 @@ these rules. The methods of :class:`Template` are: ...@@ -168,7 +168,7 @@ these rules. The methods of :class:`Template` are:
This is the object passed to the constructor's *template* argument. In general, This is the object passed to the constructor's *template* argument. In general,
you shouldn't change it, but read-only access is not enforced. you shouldn't change it, but read-only access is not enforced.
Here is an example of how to use a Template:: Here is an example of how to use a Template:
>>> from string import Template >>> from string import Template
>>> s = Template('$who likes $what') >>> s = Template('$who likes $what')
......
...@@ -382,11 +382,12 @@ The module defines the following functions and data items: ...@@ -382,11 +382,12 @@ The module defines the following functions and data items:
The default values used to fill in any missing data when more accurate values The default values used to fill in any missing data when more accurate values
cannot be inferred are ``(1900, 1, 1, 0, 0, 0, 0, 1, -1)``. cannot be inferred are ``(1900, 1, 1, 0, 0, 0, 0, 1, -1)``.
For example:: For example:
>>> import time >>> import time
>>> time.strptime("30 Nov 00", "%d %b %y") >>> time.strptime("30 Nov 00", "%d %b %y") # doctest: +NORMALIZE_WHITESPACE
(2000, 11, 30, 0, 0, 0, 3, 335, -1) time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
Support for the ``%Z`` directive is based on the values contained in ``tzname`` Support for the ``%Z`` directive is based on the values contained in ``tzname``
and whether ``daylight`` is true. Because of this, it is platform-specific and whether ``daylight`` is true. Because of this, it is platform-specific
......
...@@ -150,8 +150,9 @@ In addition, the module exposes the following constant: ...@@ -150,8 +150,9 @@ In addition, the module exposes the following constant:
.. versionadded:: 2.5 .. versionadded:: 2.5
Examples:: Examples:
>>> import unicodedata
>>> unicodedata.lookup('LEFT CURLY BRACKET') >>> unicodedata.lookup('LEFT CURLY BRACKET')
u'{' u'{'
>>> unicodedata.name(u'/') >>> unicodedata.name(u'/')
......
...@@ -38,12 +38,13 @@ The :mod:`urlparse` module defines the following functions: ...@@ -38,12 +38,13 @@ The :mod:`urlparse` module defines the following functions:
smaller parts (for example, the network location is a single string), and % smaller parts (for example, the network location is a single string), and %
escapes are not expanded. The delimiters as shown above are not part of the escapes are not expanded. The delimiters as shown above are not part of the
result, except for a leading slash in the *path* component, which is retained if result, except for a leading slash in the *path* component, which is retained if
present. For example:: present. For example:
>>> from urlparse import urlparse >>> from urlparse import urlparse
>>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html') >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
>>> o >>> o # doctest: +NORMALIZE_WHITESPACE
('http', 'www.cwi.nl:80', '/%7Eguido/Python.html', '', '', '') ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
params='', query='', fragment='')
>>> o.scheme >>> o.scheme
'http' 'http'
>>> o.port >>> o.port
...@@ -164,7 +165,7 @@ The :mod:`urlparse` module defines the following functions: ...@@ -164,7 +165,7 @@ The :mod:`urlparse` module defines the following functions:
Construct a full ("absolute") URL by combining a "base URL" (*base*) with Construct a full ("absolute") URL by combining a "base URL" (*base*) with
another URL (*url*). Informally, this uses components of the base URL, in another URL (*url*). Informally, this uses components of the base URL, in
particular the addressing scheme, the network location and (part of) the path, particular the addressing scheme, the network location and (part of) the path,
to provide missing components in the relative URL. For example:: to provide missing components in the relative URL. For example:
>>> from urlparse import urljoin >>> from urlparse import urljoin
>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html') >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
...@@ -178,7 +179,7 @@ The :mod:`urlparse` module defines the following functions: ...@@ -178,7 +179,7 @@ The :mod:`urlparse` module defines the following functions:
If *url* is an absolute URL (that is, starting with ``//`` or ``scheme://``), If *url* is an absolute URL (that is, starting with ``//`` or ``scheme://``),
the *url*'s host name and/or scheme will be present in the result. For example: the *url*'s host name and/or scheme will be present in the result. For example:
:: .. doctest::
>>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
... '//www.python.org/%7Eguido') ... '//www.python.org/%7Eguido')
...@@ -229,7 +230,7 @@ described in those functions, as well as provide an additional method: ...@@ -229,7 +230,7 @@ described in those functions, as well as provide an additional method:
and fragment identifiers will be removed. and fragment identifiers will be removed.
The result of this method is a fixpoint if passed back through the original The result of this method is a fixpoint if passed back through the original
parsing function:: parsing function:
>>> import urlparse >>> import urlparse
>>> url = 'HTTP://www.Python.org/doc/#' >>> url = 'HTTP://www.Python.org/doc/#'
......
...@@ -243,7 +243,7 @@ Weak Reference Objects ...@@ -243,7 +243,7 @@ Weak Reference Objects
---------------------- ----------------------
Weak reference objects have no attributes or methods, but do allow the referent Weak reference objects have no attributes or methods, but do allow the referent
to be obtained, if it still exists, by calling it:: to be obtained, if it still exists, by calling it:
>>> import weakref >>> import weakref
>>> class Object: >>> class Object:
...@@ -256,7 +256,7 @@ to be obtained, if it still exists, by calling it:: ...@@ -256,7 +256,7 @@ to be obtained, if it still exists, by calling it::
True True
If the referent no longer exists, calling the reference object returns If the referent no longer exists, calling the reference object returns
:const:`None`:: :const:`None`:
>>> del o, o2 >>> del o, o2
>>> print r() >>> print r()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment