diff options
Diffstat (limited to 'Doc/library')
-rw-r--r-- | Doc/library/base64.rst | 2 | ||||
-rw-r--r-- | Doc/library/bisect.rst | 2 | ||||
-rw-r--r-- | Doc/library/collections.rst | 88 | ||||
-rw-r--r-- | Doc/library/cookie.rst | 11 | ||||
-rw-r--r-- | Doc/library/datetime.rst | 34 | ||||
-rw-r--r-- | Doc/library/decimal.rst | 95 | ||||
-rw-r--r-- | Doc/library/difflib.rst | 65 | ||||
-rw-r--r-- | Doc/library/fnmatch.rst | 2 | ||||
-rw-r--r-- | Doc/library/fractions.rst | 10 | ||||
-rw-r--r-- | Doc/library/functions.rst | 53 | ||||
-rw-r--r-- | Doc/library/functools.rst | 6 | ||||
-rw-r--r-- | Doc/library/getopt.rst | 7 | ||||
-rw-r--r-- | Doc/library/hashlib.rst | 4 | ||||
-rw-r--r-- | Doc/library/heapq.rst | 3 | ||||
-rw-r--r-- | Doc/library/itertools.rst | 15 | ||||
-rw-r--r-- | Doc/library/operator.rst | 29 | ||||
-rw-r--r-- | Doc/library/pprint.rst | 29 | ||||
-rw-r--r-- | Doc/library/random.rst | 9 | ||||
-rw-r--r-- | Doc/library/re.rst | 159 | ||||
-rw-r--r-- | Doc/library/sched.rst | 2 | ||||
-rw-r--r-- | Doc/library/select.rst | 40 | ||||
-rw-r--r-- | Doc/library/stdtypes.rst | 25 | ||||
-rw-r--r-- | Doc/library/string.rst | 2 | ||||
-rw-r--r-- | Doc/library/time.rst | 7 | ||||
-rw-r--r-- | Doc/library/unicodedata.rst | 3 | ||||
-rw-r--r-- | Doc/library/urlparse.rst | 13 | ||||
-rw-r--r-- | Doc/library/weakref.rst | 44 |
27 files changed, 432 insertions, 327 deletions
diff --git a/Doc/library/base64.rst b/Doc/library/base64.rst index daa8fd5..68a941f 100644 --- a/Doc/library/base64.rst +++ b/Doc/library/base64.rst @@ -150,7 +150,7 @@ The legacy interface: :func:`encodestring` returns a string containing one or more lines of base64-encoded data always including an extra trailing newline (``'\n'``). -An example usage of the module:: +An example usage of the module: >>> import base64 >>> encoded = base64.b64encode('data to be encoded') diff --git a/Doc/library/bisect.rst b/Doc/library/bisect.rst index 114300e..9e77699 100644 --- a/Doc/library/bisect.rst +++ b/Doc/library/bisect.rst @@ -64,7 +64,7 @@ Examples 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 (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" >>> breakpoints = [30, 44, 66, 75, 85] diff --git a/Doc/library/collections.rst b/Doc/library/collections.rst index 55b6f37..7966a2e 100644 --- a/Doc/library/collections.rst +++ b/Doc/library/collections.rst @@ -7,6 +7,11 @@ .. moduleauthor:: Raymond Hettinger <python@rcn.com> .. sectionauthor:: Raymond Hettinger <python@rcn.com> +.. testsetup:: * + + from collections import * + import itertools + __name__ = '<doctest>' This module implements high-performance container datatypes. Currently, there are two datatypes, :class:`deque` and :class:`defaultdict`, and @@ -16,14 +21,14 @@ be useful when inheriting directly from :class:`dict` or :class:`list` isn't convenient. The specialized containers provided in this module provide alternatives -to Python's general purpose built-in containers, :class:`dict`, +to Python's general purpose built-in containers, :class:`dict`, :class:`list`, :class:`set`, and :class:`tuple`. Besides the containers provided here, the optional :mod:`bsddb` -module offers the ability to create in-memory or file based ordered +module offers the ability to create in-memory or file based ordered dictionaries with string keys using the :meth:`bsddb.btopen` method. In addition to containers, the collections module provides some ABCs -(abstract base classes). These can be used to test whether a class +(abstract base classes) that can be used to test whether a class provides a particular interface, for example, is it hashable or a mapping, and some of them can also be used as mixin classes. @@ -104,15 +109,15 @@ The ABC supplies the remaining methods such as :meth:`__and__` and Notes on using :class:`Set` and :class:`MutableSet` as a mixin: -(1) +(1) Since some set operations create new sets, the default mixin methods need - a way to create new instances from an iterable. The class constructor is - assumed to have a signature in the form ``ClassName(iterable)``. + a way to create new instances from an iterable. The class constructor is + assumed to have a signature in the form ``ClassName(iterable)``. That assumption is factored-out to a single internal classmethod called :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set. If the :class:`Set` mixin is being used in a class with a different - constructor signature, you will need to override :meth:`from_iterable` - with a classmethod that can construct new instances from + constructor signature, you will need to override :meth:`from_iterable` + with a classmethod that can construct new instances from an iterable argument. (2) @@ -219,12 +224,14 @@ In addition to the above, deques support iteration, pickling, ``len(d)``, ``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with the :keyword:`in` operator, and subscript references such as ``d[-1]``. -Example:: +Example: + +.. doctest:: >>> from collections import deque >>> d = deque('ghi') # make a new deque with three items >>> for elem in d: # iterate over the deque's elements - ... print(elem.upper()) + ... print elem.upper() G H I @@ -303,7 +310,7 @@ a reduction function, and calling :meth:`append` to add the result back to the deque. For example, building a balanced binary tree of nested lists entails reducing -two adjacent nodes into one by grouping them in a list:: +two adjacent nodes into one by grouping them in a list: >>> def maketree(iterable): ... d = deque(iterable) @@ -375,7 +382,7 @@ standard :class:`dict` operations: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Using :class:`list` as the :attr:`default_factory`, it is easy to group a -sequence of key-value pairs into a dictionary of lists:: +sequence of key-value pairs into a dictionary of lists: >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>> d = defaultdict(list) @@ -391,7 +398,7 @@ function which returns an empty :class:`list`. The :meth:`list.append` operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the :meth:`list.append` operation adds another value to the list. This technique is -simpler and faster than an equivalent technique using :meth:`dict.setdefault`:: +simpler and faster than an equivalent technique using :meth:`dict.setdefault`: >>> d = {} >>> for k, v in s: @@ -402,7 +409,7 @@ simpler and faster than an equivalent technique using :meth:`dict.setdefault`:: Setting the :attr:`default_factory` to :class:`int` makes the :class:`defaultdict` useful for counting (like a bag or multiset in other -languages):: +languages): >>> s = 'mississippi' >>> d = defaultdict(int) @@ -419,7 +426,7 @@ zero. The increment operation then builds up the count for each letter. The function :func:`int` which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use a lambda function which can supply any constant value (not just -zero):: +zero): >>> def constant_factory(value): ... return lambda: value @@ -429,7 +436,7 @@ zero):: 'John ran to <missing>' Setting the :attr:`default_factory` to :class:`set` makes the -:class:`defaultdict` useful for building a dictionary of sets:: +:class:`defaultdict` useful for building a dictionary of sets: >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)] >>> d = defaultdict(set) @@ -472,41 +479,44 @@ they add the ability to access fields by name instead of position index. Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples. -Example:: +Example: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE >>> Point = namedtuple('Point', 'x y', verbose=True) class Point(tuple): 'Point(x, y)' - + <BLANKLINE> __slots__ = () - + <BLANKLINE> _fields = ('x', 'y') - + <BLANKLINE> def __new__(cls, x, y): return tuple.__new__(cls, (x, y)) - + <BLANKLINE> @classmethod - def _make(cls, iterable): + def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new Point object from a sequence or iterable' - result = tuple.__new__(cls, iterable) + result = new(cls, iterable) if len(result) != 2: raise TypeError('Expected 2 arguments, got %d' % len(result)) return result - + <BLANKLINE> def __repr__(self): return 'Point(x=%r, y=%r)' % self - + <BLANKLINE> def _asdict(t): 'Return a new dict which maps field names to their values' return {'x': t[0], 'y': t[1]} - + <BLANKLINE> def _replace(self, **kwds): 'Return a new Point object replacing specified fields with new values' result = self._make(map(kwds.pop, ('x', 'y'), self)) if kwds: raise ValueError('Got unexpected field names: %r' % kwds.keys()) return result - + <BLANKLINE> x = property(itemgetter(0)) y = property(itemgetter(1)) @@ -545,7 +555,7 @@ field names, the method and attribute names start with an underscore. Class method that makes a new instance from an existing sequence or iterable. -:: +.. doctest:: >>> t = [11, 22] >>> Point._make(t) @@ -553,16 +563,15 @@ field names, the method and attribute names start with an underscore. .. method:: somenamedtuple._asdict() - Return a new dict which maps field names to their corresponding values: - -:: + Return a new dict which maps field names to their corresponding values:: >>> p._asdict() {'x': 11, 'y': 22} - + .. method:: somenamedtuple._replace(kwargs) - Return a new instance of the named tuple replacing specified fields with new values: + Return a new instance of the named tuple replacing specified fields with new + values: :: @@ -578,7 +587,7 @@ field names, the method and attribute names start with an underscore. Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples. -:: +.. doctest:: >>> p._fields # view the field names ('x', 'y') @@ -589,12 +598,12 @@ field names, the method and attribute names start with an underscore. Pixel(x=11, y=22, red=128, green=255, blue=0) To retrieve a field whose name is stored in a string, use the :func:`getattr` -function:: +function: >>> getattr(p, 'x') 11 -To convert a dictionary to a named tuple, use the double-star-operator [#]_:: +To convert a dictionary to a named tuple, use the double-star-operator [#]_: >>> d = {'x': 11, 'y': 22} >>> Point(**d) @@ -602,7 +611,7 @@ To convert a dictionary to a named tuple, use the double-star-operator [#]_:: Since a named tuple is a regular Python class, it is easy to add or change functionality with a subclass. Here is how to add a calculated field and -a fixed-width print format:: +a fixed-width print format: >>> class Point(namedtuple('Point', 'x y')): ... __slots__ = () @@ -614,7 +623,6 @@ a fixed-width print format:: >>> for p in Point(3, 4), Point(14, 5/7.): ... print(p) - Point: x= 3.000 y= 4.000 hypot= 5.000 Point: x=14.000 y= 0.714 hypot=14.018 @@ -623,12 +631,12 @@ keep memory requirements low by preventing the creation of instance dictionaries Subclassing is not useful for adding new, stored fields. Instead, simply -create a new named tuple type from the :attr:`_fields` attribute:: +create a new named tuple type from the :attr:`_fields` attribute: >>> Point3D = namedtuple('Point3D', Point._fields + ('z',)) Default values can be implemented by using :meth:`_replace` to -customize a prototype instance:: +customize a prototype instance: >>> Account = namedtuple('Account', 'owner balance transaction_count') >>> default_account = Account('<owner name>', 0.0, 0) diff --git a/Doc/library/cookie.rst b/Doc/library/cookie.rst index 84ac72a..ccc2faa 100644 --- a/Doc/library/cookie.rst +++ b/Doc/library/cookie.rst @@ -206,7 +206,10 @@ Morsel Objects 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 >>> C = Cookie.SimpleCookie() @@ -215,11 +218,11 @@ The following example demonstrates how to use the :mod:`Cookie` module. :: >>> C["fig"] = "newton" >>> C["sugar"] = "wafer" >>> print(C) # generate HTTP headers - Set-Cookie: sugar=wafer Set-Cookie: fig=newton - >>> print(C.output()) # same thing Set-Cookie: sugar=wafer + >>> print(C.output()) # same thing Set-Cookie: fig=newton + Set-Cookie: sugar=wafer >>> C = Cookie.SmartCookie() >>> C["rocky"] = "road" >>> C["rocky"]["path"] = "/cookie" @@ -230,8 +233,8 @@ The following example demonstrates how to use the :mod:`Cookie` module. :: >>> C = Cookie.SmartCookie() >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header) >>> print(C) - Set-Cookie: vienna=finger Set-Cookie: chips=ahoy + Set-Cookie: vienna=finger >>> C = Cookie.SmartCookie() >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') >>> print(C) diff --git a/Doc/library/datetime.rst b/Doc/library/datetime.rst index 8db1cb5..868cbd8 100644 --- a/Doc/library/datetime.rst +++ b/Doc/library/datetime.rst @@ -157,7 +157,7 @@ dates or times. :exc:`OverflowError` is raised. Note that normalization of negative values may be surprising at first. For - example, :: + example, >>> from datetime import timedelta >>> d = timedelta(microseconds=-1) @@ -263,7 +263,7 @@ comparison is ``==`` or ``!=``. The latter cases return :const:`False` or efficient pickling, and in Boolean contexts, a :class:`timedelta` object is considered to be true if and only if it isn't equal to ``timedelta(0)``. -Example usage:: +Example usage: >>> from datetime import timedelta >>> year = timedelta(days=365) @@ -522,14 +522,16 @@ Example of counting days to an event:: >>> time_to_birthday.days 202 -Example of working with :class:`date`:: +Example of working with :class:`date`: + +.. doctest:: >>> from datetime import date >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001 >>> d datetime.date(2002, 3, 11) >>> t = d.timetuple() - >>> for i in t: + >>> for i in t: # doctest: +SKIP ... print i 2002 # year 3 # month @@ -541,8 +543,8 @@ Example of working with :class:`date`:: 70 # 70th day in the year -1 >>> ic = d.isocalendar() - >>> for i in ic: - ... print i # doctest: +SKIP + >>> for i in ic: # doctest: +SKIP + ... print i 2002 # ISO year 11 # ISO week number 1 # ISO day number ( 1 = Monday ) @@ -957,7 +959,7 @@ Instance methods: YYYY-MM-DDTHH:MM:SS+HH:MM The optional argument *sep* (default ``'T'``) is a one-character separator, - placed between the date and time portions of the result. For example, :: + placed between the date and time portions of the result. For example, >>> from datetime import tzinfo, timedelta, datetime >>> class TZ(tzinfo): @@ -987,8 +989,10 @@ Instance methods: Return a string representing the date and time, controlled by an explicit format string. See section :ref:`strftime-behavior`. -Examples of working with datetime objects:: - +Examples of working with datetime objects: + +.. doctest:: + >>> from datetime import datetime, date, time >>> # Using datetime.combine() >>> d = date(2005, 7, 14) @@ -996,9 +1000,9 @@ Examples of working with datetime objects:: >>> datetime.combine(d, t) datetime.datetime(2005, 7, 14, 12, 30) >>> # Using datetime.now() or datetime.utcnow() - >>> datetime.now() + >>> datetime.now() # doctest: +SKIP datetime.datetime(2007, 12, 6, 16, 29, 43, 79043) # GMT +1 - >>> datetime.utcnow() + >>> datetime.utcnow() # doctest: +SKIP datetime.datetime(2007, 12, 6, 15, 29, 43, 79060) >>> # Using datetime.strptime() >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") @@ -1006,7 +1010,7 @@ Examples of working with datetime objects:: datetime.datetime(2006, 11, 21, 16, 30) >>> # Using datetime.timetuple() to get tuple of all attributes >>> tt = dt.timetuple() - >>> for it in tt: + >>> for it in tt: # doctest: +SKIP ... print it ... 2006 # year @@ -1020,7 +1024,7 @@ Examples of working with datetime objects:: -1 # dst - method tzinfo.dst() returned None >>> # Date in ISO format >>> ic = dt.isocalendar() - >>> for it in ic: + >>> for it in ic: # doctest: +SKIP ... print it ... 2006 # ISO year @@ -1030,7 +1034,7 @@ Examples of working with datetime objects:: >>> dt.strftime("%A, %d. %B %Y %I:%M%p") 'Tuesday, 21. November 2006 04:30PM' -Using datetime with tzinfo:: +Using datetime with tzinfo: >>> from datetime import timedelta, datetime, tzinfo >>> class GMT1(tzinfo): @@ -1232,7 +1236,7 @@ Instance methods: ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't return ``None`` or a string object. -Example:: +Example: >>> from datetime import time, tzinfo >>> class GMT1(tzinfo): diff --git a/Doc/library/decimal.rst b/Doc/library/decimal.rst index ac21b57..04433c1 100644 --- a/Doc/library/decimal.rst +++ b/Doc/library/decimal.rst @@ -12,6 +12,14 @@ .. moduleauthor:: Tim Peters <tim.one at comcast.net> .. sectionauthor:: Raymond D. Hettinger <python at rcn.com> +.. import modules for testing inline doctests with the Sphinx doctest builder +.. testsetup:: * + + import decimal + import math + from decimal import * + # make sure each group gets a fresh context + setcontext(Context()) The :mod:`decimal` module provides support for decimal floating point arithmetic. It offers several advantages over the :class:`float` datatype: @@ -42,7 +50,7 @@ arithmetic. It offers several advantages over the :class:`float` datatype: * Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for - a given problem:: + a given problem: >>> getcontext().prec = 6 >>> Decimal(1) / Decimal(7) @@ -115,8 +123,8 @@ precision, rounding, or enabled traps:: >>> from decimal import * >>> getcontext() Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, - capitals=1, flags=[], traps=[Overflow, InvalidOperation, - DivisionByZero]) + capitals=1, flags=[], traps=[Overflow, DivisionByZero, + InvalidOperation]) >>> getcontext().prec = 7 # Set a new precision @@ -125,7 +133,7 @@ create a Decimal from a :class:`float`, first convert it to a string. This serves as an explicit reminder of the details of the conversion (including representation error). Decimal numbers include special values such as :const:`NaN` which stands for "Not a number", positive and negative -:const:`Infinity`, and :const:`-0`. :: +:const:`Infinity`, and :const:`-0`. >>> Decimal(10) Decimal('10') @@ -144,7 +152,9 @@ representation error). Decimal numbers include special values such as The significance of a new Decimal is determined solely by the number of digits input. Context precision and rounding only come into play during arithmetic -operations. :: +operations. + +.. doctest:: newcontext >>> getcontext().prec = 6 >>> Decimal('3.0') @@ -158,7 +168,10 @@ operations. :: Decimal('5.85988') Decimals interact well with much of the rest of Python. Here is a small decimal -floating point flying circus:: +floating point flying circus: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()) >>> max(data) @@ -186,7 +199,7 @@ floating point flying circus:: >>> c % a Decimal('0.77') -And some mathematical functions are also available to Decimal:: +And some mathematical functions are also available to Decimal: >>> Decimal(2).sqrt() Decimal('1.414213562373095048801688724') @@ -199,7 +212,7 @@ And some mathematical functions are also available to Decimal:: The :meth:`quantize` method rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of -places:: +places: >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN) Decimal('7.32') @@ -217,7 +230,10 @@ function. In accordance with the standard, the :mod:`Decimal` module provides two ready to use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The former is especially useful for debugging because many of the traps are -enabled:: +enabled: + +.. doctest:: newcontext + :options: +NORMALIZE_WHITESPACE >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN) >>> setcontext(myothercontext) @@ -251,15 +267,18 @@ using the :meth:`clear_flags` method. :: Decimal('3.14159292') >>> getcontext() Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, - capitals=1, flags=[Inexact, Rounded], traps=[]) + capitals=1, flags=[Rounded, Inexact], traps=[]) The *flags* entry shows that the rational approximation to :const:`Pi` was rounded (digits beyond the context precision were thrown away) and that the result is inexact (some of the discarded digits were non-zero). Individual traps are set using the dictionary in the :attr:`traps` field of a -context:: +context: +.. doctest:: newcontext + + >>> setcontext(ExtendedContext) >>> Decimal(1) / Decimal(0) Decimal('Infinity') >>> getcontext().traps[DivisionByZero] = 1 @@ -387,7 +406,7 @@ also have a number of specialized methods: but the result gives a total ordering on :class:`Decimal` instances. Two :class:`Decimal` instances with the same numeric value but different representations compare unequal in this - ordering:: + ordering: >>> Decimal('12.0').compare_total(Decimal('12')) Decimal('-1') @@ -426,7 +445,7 @@ also have a number of specialized methods: .. method:: Decimal.copy_sign(other) Return a copy of the first operand with the sign set to be the - same as the sign of the second operand. For example:: + same as the sign of the second operand. For example: >>> Decimal('2.3').copy_sign(Decimal('-1.5')) Decimal('-2.3') @@ -934,7 +953,9 @@ method. For example, ``C.exp(x)`` is equivalent to needed by the application. Another benefit is that rounding immediately eliminates unintended effects from digits beyond the current precision. In the following example, using unrounded inputs means that adding zero to a sum can - change the result:: + change the result: + + .. doctest:: newcontext >>> getcontext().prec = 3 >>> Decimal('3.4445') + Decimal('1.0023') @@ -1187,7 +1208,9 @@ The effects of round-off error can be amplified by the addition or subtraction of nearly offsetting quantities resulting in loss of significance. Knuth provides two instructive examples where rounded floating point arithmetic with insufficient precision causes the breakdown of the associative and distributive -properties of addition:: +properties of addition: + +.. doctest:: newcontext # Examples from Seminumerical Algorithms, Section 4.2.2. >>> from decimal import Decimal, getcontext @@ -1206,7 +1229,9 @@ properties of addition:: Decimal('0.0060000') The :mod:`decimal` module makes it possible to restore the identities by -expanding the precision sufficiently to avoid loss of significance:: +expanding the precision sufficiently to avoid loss of significance: + +.. doctest:: newcontext >>> getcontext().prec = 20 >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111') @@ -1272,7 +1297,7 @@ In addition to the two signed zeros which are distinct yet equal, there are various representations of zero with differing precisions yet equivalent in value. This takes a bit of getting used to. For an eye accustomed to normalized floating point representations, it is not immediately obvious that -the following calculation returns a value equal to zero:: +the following calculation returns a value equal to zero: >>> 1 / Decimal('Infinity') Decimal('0E-1000000026') @@ -1474,7 +1499,7 @@ Decimal FAQ Q. It is cumbersome to type ``decimal.Decimal('1234.5')``. Is there a way to minimize typing when using the interactive interpreter? -A. Some users abbreviate the constructor to just a single letter:: +A. Some users abbreviate the constructor to just a single letter: >>> D = decimal.Decimal >>> D('1.23') + D('3.45') @@ -1485,7 +1510,7 @@ places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used? A. The :meth:`quantize` method rounds to a fixed number of decimal places. If -the :const:`Inexact` trap is set, it is also useful for validation:: +the :const:`Inexact` trap is set, it is also useful for validation: >>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01') @@ -1500,7 +1525,7 @@ the :const:`Inexact` trap is set, it is also useful for validation:: >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact])) Traceback (most recent call last): ... - Inexact: Changed in rounding + Inexact Q. Once I have valid two place inputs, how do I maintain that invariant throughout an application? @@ -1508,7 +1533,7 @@ throughout an application? A. Some operations like addition, subtraction, and multiplication by an integer will automatically preserve fixed point. Others operations, like division and non-integer multiplication, will change the number of decimal places and need to -be followed-up with a :meth:`quantize` step:: +be followed-up with a :meth:`quantize` step: >>> a = Decimal('102.72') # Initial fixed-point values >>> b = Decimal('3.17') @@ -1524,7 +1549,7 @@ be followed-up with a :meth:`quantize` step:: Decimal('0.03') In developing fixed-point applications, it is convenient to define functions -to handle the :meth:`quantize` step:: +to handle the :meth:`quantize` step: >>> def mul(x, y, fp=TWOPLACES): ... return (x * y).quantize(fp) @@ -1542,7 +1567,7 @@ various precisions. Is there a way to transform them to a single recognizable canonical value? A. The :meth:`normalize` method maps all equivalent values to a single -representative:: +representative: >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split()) >>> [v.normalize() for v in values] @@ -1558,7 +1583,7 @@ original's two-place significance. If an application does not care about tracking significance, it is easy to remove the exponent and trailing zeroes, losing significance, but keeping the -value unchanged:: +value unchanged: >>> def remove_exponent(d): ... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize() @@ -1570,7 +1595,9 @@ Q. Is there a way to convert a regular float to a :class:`Decimal`? A. Yes, all binary floating point numbers can be exactly expressed as a Decimal. An exact conversion may take more precision than intuition would -suggest, so we trap :const:`Inexact` to signal a need for more precision:: +suggest, so we trap :const:`Inexact` to signal a need for more precision: + +.. testcode:: def float_to_decimal(f): "Convert a floating point number to a Decimal with no loss of information" @@ -1583,6 +1610,8 @@ suggest, so we trap :const:`Inexact` to signal a need for more precision:: except Inexact: ctx.prec += 1 +.. doctest:: + >>> float_to_decimal(math.pi) Decimal('3.141592653589793115997963468544185161590576171875') @@ -1590,7 +1619,7 @@ Q. Why isn't the :func:`float_to_decimal` routine included in the module? A. There is some question about whether it is advisable to mix binary and decimal floating point. Also, its use requires some care to avoid the -representation issues associated with binary floating point:: +representation issues associated with binary floating point: >>> float_to_decimal(1.1) Decimal('1.100000000000000088817841970012523233890533447265625') @@ -1610,23 +1639,27 @@ different precisions? A. Yes. The principle is that all values are considered to be exact and so is the arithmetic on those values. Only the results are rounded. The advantage for inputs is that "what you type is what you get". A disadvantage is that the -results can look odd if you forget that the inputs haven't been rounded:: +results can look odd if you forget that the inputs haven't been rounded: + +.. doctest:: newcontext >>> getcontext().prec = 3 - >>> Decimal('3.104') + D('2.104') + >>> Decimal('3.104') + Decimal('2.104') Decimal('5.21') - >>> Decimal('3.104') + D('0.000') + D('2.104') + >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104') Decimal('5.20') The solution is either to increase precision or to force rounding of inputs -using the unary plus operation:: +using the unary plus operation: + +.. doctest:: newcontext >>> getcontext().prec = 3 >>> +Decimal('1.23456789') # unary plus triggers rounding Decimal('1.23') Alternatively, inputs can be rounded upon creation using the -:meth:`Context.create_decimal` method:: +:meth:`Context.create_decimal` method: >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678') Decimal('1.2345') diff --git a/Doc/library/difflib.rst b/Doc/library/difflib.rst index 66f64e5..db4bd3a 100644 --- a/Doc/library/difflib.rst +++ b/Doc/library/difflib.rst @@ -1,4 +1,3 @@ - :mod:`difflib` --- Helpers for computing deltas =============================================== @@ -8,7 +7,10 @@ .. sectionauthor:: Tim Peters <tim_one@users.sourceforge.net> .. Markup by Fred L. Drake, Jr. <fdrake@acm.org> +.. testsetup:: + import sys + from difflib import * This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce difference @@ -144,12 +146,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 strings default to blanks. - :: - >>> s1 = ['bacon\n', 'eggs\n', 'ham\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'): - ... sys.stdout.write(line) + ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE *** before.py --- after.py *************** @@ -180,7 +180,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. 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']) ['apple', 'ape'] @@ -215,7 +215,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module. function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a 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), ... 'ore\ntree\nemu\n'.splitlines(1)) @@ -239,7 +239,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 prefixes. - Example:: + Example: >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) @@ -279,12 +279,11 @@ 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 strings default to blanks. - :: >>> s1 = ['bacon\n', 'eggs\n', 'ham\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'): - ... sys.stdout.write(line) + ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE --- before.py +++ after.py @@ -1,4 +1,4 @@ @@ -379,11 +378,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 == 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 - 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.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 above, but with the additional restriction that no junk element appears in the @@ -394,11 +393,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 prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the second 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.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)``. @@ -420,11 +419,11 @@ use :meth:`set_seq2` to set the commonly used sequence once and call .. XXX Explain why a dummy is used! - :: + .. doctest:: >>> s = SequenceMatcher(None, "abxcd", "abcd") >>> 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() @@ -453,7 +452,7 @@ use :meth:`set_seq2` to set the commonly used sequence once and call | | are equal). | +---------------+---------------------------------------------+ - For example:: + For example: >>> a = "qabxcd" >>> b = "abycdf" @@ -509,7 +508,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 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:`ratio`:: +:meth:`ratio`: >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() @@ -525,7 +524,7 @@ different results due to differing levels of approximation, although 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 == " ", ... "private Thread currentThread;", @@ -533,19 +532,18 @@ This example compares two strings, considering blanks to be "junk:" :: :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 are close matches:: +sequences are close matches: >>> print(round(s.ratio(), 3)) 0.866 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(): ... print("a[%d] and b[%d] match for %d elements" % block) a[0] and b[0] match for 8 elements - a[8] and b[17] match for 6 elements - a[14] and b[23] match for 15 elements + a[8] and b[17] match for 21 elements a[29] and b[38] match for 0 elements Note that the last tuple returned by :meth:`get_matching_blocks` is always a @@ -553,14 +551,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``. 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(): ... print("%6s a[%d:%d] b[%d:%d]" % opcode) equal a[0:8] b[0:8] insert a[8:8] b[8:17] - equal a[8:14] b[17:23] - equal a[14:29] b[23:38] + equal a[8:29] b[17:38] 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. @@ -613,7 +610,7 @@ Differ Example 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 -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. ... 2. Explicit is better than implicit. @@ -630,7 +627,7 @@ obtained from the :meth:`readlines` method of file-like objects):: ... 5. Flat is better than nested. ... '''.splitlines(1) -Next we instantiate a Differ object:: +Next we instantiate a Differ object: >>> d = Differ() @@ -638,11 +635,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 details. -Finally, we compare the two:: +Finally, we compare the two: >>> 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 >>> pprint(result) @@ -650,14 +647,14 @@ Finally, we compare the two:: '- 2. Explicit is better than implicit.\n', '- 3. Simple is better than complex.\n', '+ 3. Simple is better than complex.\n', - '? ++ \n', + '? ++\n', '- 4. Complex is better than complicated.\n', - '? ^ ---- ^ \n', + '? ^ ---- ^\n', '+ 4. Complicated is better than complex.\n', - '? ++++ ^ ^ \n', + '? ++++ ^ ^\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 >>> sys.stdout.writelines(result) @@ -682,7 +679,7 @@ This example shows how to use difflib to create a ``diff``-like utility. It is also contained in the Python source distribution, as :file:`Tools/scripts/diff.py`. -:: +.. testcode:: """ Command line interface to difflib.py providing diffs in four formats: diff --git a/Doc/library/fnmatch.rst b/Doc/library/fnmatch.rst index a75ca7c..1bb2cf2 100644 --- a/Doc/library/fnmatch.rst +++ b/Doc/library/fnmatch.rst @@ -70,7 +70,7 @@ patterns. Return the shell-style *pattern* converted to a regular expression. - Example:: + Example: >>> import fnmatch, re >>> diff --git a/Doc/library/fractions.rst b/Doc/library/fractions.rst index 9ef1230..e868e57 100644 --- a/Doc/library/fractions.rst +++ b/Doc/library/fractions.rst @@ -50,18 +50,19 @@ Rational number class. Finds and returns the closest :class:`Fraction` to ``self`` that 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(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 >>> Fraction.from_float(cos(pi/3)) Fraction(4503599627370497L, 9007199254740992L) >>> Fraction.from_float(cos(pi/3)).limit_denominator() - Fraction(1, 2) + Fraction(1L, 2L) .. method:: Fraction.__floor__() @@ -90,4 +91,3 @@ Rational number class. Module :mod:`numbers` The abstract base classes making up the numeric tower. - diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst index 6ab85f6..3c27d82 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -288,7 +288,22 @@ available. They are listed here in alphabetical order. class's attributes, and recursively of the attributes of its class's base classes. - The resulting list is sorted alphabetically. + The resulting list is sorted alphabetically. For example: + + >>> import struct + >>> dir() # doctest: +SKIP + ['__builtins__', '__doc__', '__name__', 'struct'] + >>> dir(struct) # doctest: +NORMALIZE_WHITESPACE + ['Struct', '__builtins__', '__doc__', '__file__', '__name__', + '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', + 'unpack', 'unpack_from'] + >>> class Foo(object): + ... def __dir__(self): + ... return ["kan", "ga", "roo"] + ... + >>> f = Foo() + >>> dir(f) + ['ga', 'kan', 'roo'] .. note:: @@ -318,10 +333,10 @@ available. They are listed here in alphabetical order. iterator returned by :func:`enumerate` returns a tuple containing a count (from zero) and the corresponding value obtained from iterating over *iterable*. :func:`enumerate` is useful for obtaining an indexed series: ``(0, seq[0])``, - ``(1, seq[1])``, ``(2, seq[2])``, .... For example:: + ``(1, seq[1])``, ``(2, seq[2])``, .... For example: >>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter')]: - >>> print(i, season) + ... print(i, season) 0 Spring 1 Summer 2 Fall @@ -343,7 +358,7 @@ available. They are listed here in alphabetical order. propagated. If the *locals* dictionary is omitted it defaults to the *globals* dictionary. If both dictionaries are omitted, the expression is executed in the environment where :func:`eval` is called. The return value is the result of - the evaluated expression. Syntax errors are reported as exceptions. Example:: + the evaluated expression. Syntax errors are reported as exceptions. Example: >>> x = 1 >>> eval('x+1') @@ -865,15 +880,15 @@ available. They are listed here in alphabetical order. .. XXX does accept objects with __index__ too .. function:: range([start,] stop[, step]) - This is a versatile function to create iterators containing arithmetic - progressions. It is most often used in :keyword:`for` loops. The arguments - must be integers. If the *step* argument is omitted, it defaults to ``1``. - If the *start* argument is omitted, it defaults to ``0``. The full form - returns an iterator of plain integers ``[start, start + step, start + 2 * - step, ...]``. If *step* is positive, the last element is the largest ``start - + i * step`` less than *stop*; if *step* is negative, the last element is the - smallest ``start + i * step`` greater than *stop*. *step* must not be zero - (or else :exc:`ValueError` is raised). Example:: + This is a versatile function to create lists containing arithmetic progressions. + It is most often used in :keyword:`for` loops. The arguments must be plain + integers. If the *step* argument is omitted, it defaults to ``1``. If the + *start* argument is omitted, it defaults to ``0``. The full form returns a list + of plain integers ``[start, start + step, start + 2 * step, ...]``. If *step* + is positive, the last element is the largest ``start + i * step`` less than + *stop*; if *step* is negative, the last element is the smallest ``start + i * + step`` greater than *stop*. *step* must not be zero (or else :exc:`ValueError` + is raised). Example: >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] @@ -1082,12 +1097,12 @@ available. They are listed here in alphabetical order. :noindex: Return a new type object. This is essentially a dynamic form of the - :keyword:`class` statement. The *name* string is the class name and becomes - the :attr:`__name__` attribute; the *bases* tuple itemizes the base classes - and becomes the :attr:`__bases__` attribute; and the *dict* dictionary is the - namespace containing definitions for class body and becomes the - :attr:`__dict__` attribute. For example, the following two statements create - identical :class:`type` objects:: + :keyword:`class` statement. The *name* string is the class name and becomes the + :attr:`__name__` attribute; the *bases* tuple itemizes the base classes and + becomes the :attr:`__bases__` attribute; and the *dict* dictionary is the + namespace containing definitions for class body and becomes the :attr:`__dict__` + attribute. For example, the following two statements create identical + :class:`type` objects: >>> class X(object): ... a = 1 diff --git a/Doc/library/functools.rst b/Doc/library/functools.rst index 1c8fa5b..4bec7ba 100644 --- a/Doc/library/functools.rst +++ b/Doc/library/functools.rst @@ -44,8 +44,9 @@ The :mod:`functools` module defines the following functions: 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 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.__doc__ = 'Convert base 2 string to an int.' >>> basetwo('10010') @@ -87,8 +88,9 @@ The :mod:`functools` module defines the following functions: This is a convenience function for invoking ``partial(update_wrapper, 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): ... @wraps(f) ... def wrapper(*args, **kwds): diff --git a/Doc/library/getopt.rst b/Doc/library/getopt.rst index 8b8e326..cdc40bf 100644 --- a/Doc/library/getopt.rst +++ b/Doc/library/getopt.rst @@ -77,7 +77,7 @@ exception: Alias for :exc:`GetoptError`; for backward compatibility. -An example using only Unix style options:: +An example using only Unix style options: >>> import getopt >>> args = '-a -b -cfoo -d bar a1 a2'.split() @@ -89,7 +89,7 @@ An example using only Unix style options:: >>> args ['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' >>> args = s.split() @@ -98,8 +98,7 @@ Using long option names is equally easy:: >>> optlist, args = getopt.getopt(args, 'x', [ ... 'condition=', 'output-file=', 'testing']) >>> optlist - [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', - '')] + [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')] >>> args ['a1', 'a2'] diff --git a/Doc/library/hashlib.rst b/Doc/library/hashlib.rst index f1f5237..2741265 100644 --- a/Doc/library/hashlib.rst +++ b/Doc/library/hashlib.rst @@ -61,7 +61,7 @@ spammish repetition'``:: >>> m.block_size 64 -More condensed:: +More condensed: >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest() b'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' @@ -71,7 +71,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 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.update(b"Nobody inspects the spammish repetition") diff --git a/Doc/library/heapq.rst b/Doc/library/heapq.rst index 1530144..5221c4e 100644 --- a/Doc/library/heapq.rst +++ b/Doc/library/heapq.rst @@ -68,7 +68,7 @@ The following functions are provided: if item > heap[0]: item = heapreplace(heap, item) -Example of use:: +Example of use: >>> from heapq import heappush, heappop >>> heap = [] @@ -85,7 +85,6 @@ Example of use:: >>> data.sort() >>> data == ordered True - >>> The module also offers three general purpose functions based on heaps. diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 6e7885e..0d20410 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -8,6 +8,11 @@ .. sectionauthor:: Raymond Hettinger <python@rcn.com> +.. testsetup:: + + from itertools import * + + This module implements a number of :term:`iterator` building blocks inspired by constructs from the Haskell and SML programming languages. Each has been recast in a form suitable for Python. @@ -333,7 +338,7 @@ loops that truncate the stream. n = len(pool) r = n if r is None else r indices = range(n) - cycles = range(n-r+1, n+1)[::-1] + cycles = range(n, n-r, -1) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): @@ -475,7 +480,9 @@ Examples -------- 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 >>> from operator import itemgetter @@ -518,7 +525,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 eliminate temporary variables. High speed is retained by preferring "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): return list(islice(seq, n)) diff --git a/Doc/library/operator.rst b/Doc/library/operator.rst index 590098b..047c7ec 100644 --- a/Doc/library/operator.rst +++ b/Doc/library/operator.rst @@ -6,6 +6,11 @@ .. sectionauthor:: Skip Montanaro <skip@automatrix.com> +.. testsetup:: + + import operator + from operator import itemgetter + The :mod:`operator` module exports a set of functions implemented in C corresponding to the intrinsic operators of Python. For example, @@ -346,7 +351,7 @@ objects. Be careful not to misinterpret the results of these functions; none have any measure of reliability with instance objects. - For example:: + For example: >>> class C: ... pass @@ -399,13 +404,12 @@ objects. useful than it otherwise might be. Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to -their character equivalents. :: +their character equivalents. - >>> import operator >>> d = {} >>> keys = range(256) >>> vals = map(chr, keys) - >>> map(operator.setitem, [d]*len(keys), keys, vals) + >>> map(operator.setitem, [d]*len(keys), keys, vals) # doctest: +SKIP .. XXX: find a better, readable, example @@ -444,21 +448,20 @@ expect a function argument. The items can be any type accepted by the operand's :meth:`__getitem__` method. Dictionaries accept any hashable value. Lists, tuples, and - strings accept an index or a slice:: + strings accept an index or a slice: - >>> itemgetter(1)('ABCDEFG') - 'B' - >>> itemgetter(1,3,5)('ABCDEFG') - ('B', 'D', 'F') - >>> itemgetter(slice(2,None))('ABCDEFG') - 'CDEFG' + >>> itemgetter(1)('ABCDEFG') + 'B' + >>> itemgetter(1,3,5)('ABCDEFG') + ('B', 'D', 'F') + >>> itemgetter(slice(2,None))('ABCDEFG') + 'CDEFG' .. versionadded:: 2.4 Example of using :func:`itemgetter` to retrieve specific fields from a - tuple record:: + tuple record: - >>> from operator import itemgetter >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)] >>> getcount = itemgetter(1) >>> map(getcount, inventory) diff --git a/Doc/library/pprint.rst b/Doc/library/pprint.rst index 6670cf8..3e2e892 100644 --- a/Doc/library/pprint.rst +++ b/Doc/library/pprint.rst @@ -46,14 +46,14 @@ The :mod:`pprint` module defines one class: the depth of the objects being formatted. The desired output width is constrained using the *width* parameter; the default is 80 characters. If a structure cannot be formatted within the constrained width, a best effort will - be made. :: + be made. >>> import pprint >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> stuff.insert(0, stuff[:]) >>> pp = pprint.PrettyPrinter(indent=4) >>> pp.pprint(stuff) - [ ['spam', 'eggs', 'lumberjack', 'knights', 'ni'], + [ [ 'spam', 'eggs', 'lumberjack', 'knights', 'ni'], 'spam', 'eggs', 'lumberjack', @@ -84,19 +84,18 @@ The :class:`PrettyPrinter` class supports several derivative functions: in the interactive interpreter instead of the :func:`print` function for inspecting values (you can even reassign ``print = pprint.pprint`` for use within a scope). *indent*, *width* and *depth* will be passed to the - :class:`PrettyPrinter` constructor as formatting parameters. :: + :class:`PrettyPrinter` constructor as formatting parameters. >>> import pprint >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni'] >>> stuff.insert(0, stuff) >>> pprint.pprint(stuff) - [<Recursion on list with id=869440>, - '', - '/usr/local/lib/python1.5', - '/usr/local/lib/python1.5/test', - '/usr/local/lib/python1.5/sunos5', - '/usr/local/lib/python1.5/sharedmodules', - '/usr/local/lib/python1.5/tkinter'] + [<Recursion on list with id=...>, + 'spam', + 'eggs', + 'lumberjack', + 'knights', + 'ni'] .. function:: isreadable(object) @@ -105,7 +104,7 @@ The :class:`PrettyPrinter` class supports several derivative functions: Determine if the formatted representation of *object* is "readable," or can be used to reconstruct the value using :func:`eval`. This always returns ``False`` - for recursive objects. :: + for recursive objects. >>> pprint.isreadable(stuff) False @@ -115,8 +114,8 @@ The :class:`PrettyPrinter` class supports several derivative functions: Determine if *object* requires a recursive representation. -One more support function is also defined: +One more support function is also defined: .. function:: saferepr(object) @@ -125,12 +124,8 @@ One more support function is also defined: recursive reference will be represented as ``<Recursion on typename with id=number>``. The representation is not otherwise formatted. -:: - >>> pprint.saferepr(stuff) - "[<Recursion on list with id=682968>, '', '/usr/local/lib/python1.5', '/usr/loca - l/lib/python1.5/test', '/usr/local/lib/python1.5/sunos5', '/usr/local/lib/python - 1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter']" + "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']" .. _prettyprinter-objects: diff --git a/Doc/library/random.rst b/Doc/library/random.rst index c9e703c..0b82bf4 100644 --- a/Doc/library/random.rst +++ b/Doc/library/random.rst @@ -153,6 +153,15 @@ be found in any statistics text. Return a random floating point number *N* such that ``a <= N < b``. +.. function:: triangular(low, high, mode) + + Return a random floating point number *N* such that ``low <= N < high`` + and with the specified *mode* between those bounds. + + If *mode* is not specified or is ``None``, it defaults to the midpoint + between the upper and lower bounds, producing a symmetric distribution. + + The default values for *low* and *high* are zero and one. .. function:: betavariate(alpha, beta) diff --git a/Doc/library/re.rst b/Doc/library/re.rst index d7eb6f6..019652e 100644 --- a/Doc/library/re.rst +++ b/Doc/library/re.rst @@ -264,14 +264,14 @@ The special characters are: ``abc`` or ``a|b`` are allowed, but ``a*`` and ``a{3,4}`` are not. Note that patterns which start with positive lookbehind assertions will never match at the beginning of the string being searched; you will most likely want to use the - :func:`search` function rather than the :func:`match` function:: + :func:`search` function rather than the :func:`match` function: >>> import re >>> m = re.search('(?<=abc)def', 'abcdef') >>> m.group(0) 'def' - This example looks for a word following a hyphen:: + This example looks for a word following a hyphen: >>> m = re.search('(?<=-)\w+', 'spam-egg') >>> m.group(0) @@ -400,11 +400,11 @@ beginning with ``'^'``: ``'^'`` matches only at the start of the string, or in :const:`MULTILINE` mode also immediately following a newline. The "match" operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optional *pos* -argument regardless of whether a newline precedes it. :: +argument regardless of whether a newline precedes it. - >>> re.match("c", "abcdef") # No match - >>> re.search("c", "abcdef") - <_sre.SRE_Match object at 0x827e9c0> # Match + >>> re.match("c", "abcdef") # No match + >>> re.search("c", "abcdef") # Match + <_sre.SRE_Match object at ...> .. _contents-of-module-re: @@ -541,7 +541,7 @@ form. If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string. The same holds for - the end of the string:: + the end of the string: >>> re.split('(\W+)', '...words, words...') ['', '...', 'words', ', ', 'words', '...', ''] @@ -551,7 +551,7 @@ form. in the separator, the 0th, the 2nd and so forth). Note that *split* will never split a string on an empty pattern match. - For example:: + For example: >>> re.split('x*', 'foo') ['foo'] @@ -584,7 +584,7 @@ form. converted to a single newline character, ``\r`` is converted to a linefeed, and so forth. Unknown escapes such as ``\j`` are left alone. Backreferences, such as ``\6``, are replaced with the substring matched by group 6 in the pattern. - For example:: + For example: >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):', ... r'static PyObject*\npy_\1(void)\n{', @@ -593,7 +593,7 @@ form. If *repl* is a function, it is called for every non-overlapping occurrence of *pattern*. The function takes a single match object argument, and returns the - replacement string. For example:: + replacement string. For example: >>> def dashrepl(matchobj): ... if matchobj.group(0) == '-': return ' ' @@ -674,12 +674,12 @@ attributes: from *pos* to ``endpos - 1`` will be searched for a match. If *endpos* is less than *pos*, no match will be found, otherwise, if *rx* is a compiled regular expression object, ``rx.match(string, 0, 50)`` is equivalent to - ``rx.match(string[:50], 0)``. :: + ``rx.match(string[:50], 0)``. >>> pattern = re.compile("o") >>> pattern.match("dog") # No match as "o" is not at the start of "dog." >>> pattern.match("dog", 1) # Match as "o" is the 2nd character of "dog". - <_sre.SRE_Match object at 0x827eb10> + <_sre.SRE_Match object at ...> .. method:: RegexObject.search(string[, pos[, endpos]]) @@ -767,24 +767,24 @@ support the following methods and attributes: pattern, an :exc:`IndexError` exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is ``None``. If a group is contained in a part of the pattern that matched multiple times, - the last match is returned. :: + the last match is returned. >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist") - >>> m.group(0) - 'Isaac Newton' # The entire match - >>> m.group(1) - 'Isaac' # The first parenthesized subgroup. - >>> m.group(2) - 'Newton' # The second parenthesized subgroup. - >>> m.group(1, 2) - ('Isaac', 'Newton') # Multiple arguments give us a tuple. + >>> m.group(0) # The entire match + 'Isaac Newton' + >>> m.group(1) # The first parenthesized subgroup. + 'Isaac' + >>> m.group(2) # The second parenthesized subgroup. + 'Newton' + >>> m.group(1, 2) # Multiple arguments give us a tuple. + ('Isaac', 'Newton') If the regular expression uses the ``(?P<name>...)`` syntax, the *groupN* arguments may also be strings identifying groups by their group name. If a string argument is not used as a group name in the pattern, an :exc:`IndexError` exception is raised. - A moderately complicated example:: + A moderately complicated example: >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcom Reynolds") >>> m.group('first_name') @@ -792,14 +792,15 @@ support the following methods and attributes: >>> m.group('last_name') 'Reynolds' - Named groups can also be referred to by their index:: + Named groups can also be referred to by their index: >>> m.group(1) 'Malcom' >>> m.group(2) 'Reynolds' - If a group matches multiple times, only the last match is accessible:: + If a group matches multiple times, only the last match is accessible: + >>> m = re.match(r"(..)+", "a1b2c3") # Matches 3 times. >>> m.group(1) # Returns only the last match. 'c3' @@ -811,7 +812,7 @@ support the following methods and attributes: many groups are in the pattern. The *default* argument is used for groups that did not participate in the match; it defaults to ``None``. - For example:: + For example: >>> m = re.match(r"(\d+)\.(\d+)", "24.1632") >>> m.groups() @@ -819,20 +820,20 @@ support the following methods and attributes: If we make the decimal place and everything after it optional, not all groups might participate in the match. These groups will default to ``None`` unless - the *default* argument is given:: + the *default* argument is given: >>> m = re.match(r"(\d+)\.?(\d+)?", "24") - >>> m.groups() - ('24', None) # Second group defaults to None. - >>> m.groups('0') - ('24', '0') # Now, the second group defaults to '0'. + >>> m.groups() # Second group defaults to None. + ('24', None) + >>> m.groups('0') # Now, the second group defaults to '0'. + ('24', '0') .. method:: MatchObject.groupdict([default]) Return a dictionary containing all the *named* subgroups of the match, keyed by the subgroup name. The *default* argument is used for groups that did not - participate in the match; it defaults to ``None``. For example:: + participate in the match; it defaults to ``None``. For example: >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcom Reynolds") >>> m.groupdict() @@ -855,7 +856,7 @@ support the following methods and attributes: ``m.start(0)`` is 1, ``m.end(0)`` is 2, ``m.start(1)`` and ``m.end(1)`` are both 2, and ``m.start(2)`` raises an :exc:`IndexError` exception. - An example that will remove *remove_this* from email addresses:: + An example that will remove *remove_this* from email addresses: >>> email = "tony@tiremove_thisger.net" >>> m = re.search("remove_this", email) @@ -918,7 +919,9 @@ Checking For a Pair ^^^^^^^^^^^^^^^^^^^ In this example, we'll use the following helper function to display match -objects a little more gracefully:: +objects a little more gracefully: + +.. testcode:: def displaymatch(match): if match is None: @@ -930,28 +933,30 @@ a 5-character string with each character representing a card, "a" for ace, "k" for king, "q" for queen, j for jack, "0" for 10, and "1" through "9" representing the card with that value. -To see if a given string is a valid hand, one could do the following:: +To see if a given string is a valid hand, one could do the following: - >>> valid = re.compile(r"[0-9akqj]{5}$" + >>> valid = re.compile(r"[0-9akqj]{5}$") >>> displaymatch(valid.match("ak05q")) # Valid. - <Match: 'ak05q', groups=()> + "<Match: 'ak05q', groups=()>" >>> displaymatch(valid.match("ak05e")) # Invalid. >>> displaymatch(valid.match("ak0")) # Invalid. >>> displaymatch(valid.match("727ak")) # Valid. - <Match: '727ak', groups=()> + "<Match: '727ak', groups=()>" That last hand, ``"727ak"``, contained a pair, or two of the same valued cards. -To match this with a regular expression, one could use backreferences as such:: +To match this with a regular expression, one could use backreferences as such: >>> pair = re.compile(r".*(.).*\1") >>> displaymatch(pair.match("717ak")) # Pair of 7s. - <Match: '717', groups=('7',)> + "<Match: '717', groups=('7',)>" >>> displaymatch(pair.match("718ak")) # No pairs. >>> displaymatch(pair.match("354aa")) # Pair of aces. - <Match: '345aa', groups=('a',)> + "<Match: '354aa', groups=('a',)>" To find out what card the pair consists of, one could use the :func:`group` -method of :class:`MatchObject` in the following manner:: +method of :class:`MatchObject` in the following manner: + +.. doctest:: >>> pair.match("717ak").group(1) '7' @@ -1020,7 +1025,6 @@ If you create regular expressions that require the engine to perform a lot of recursion, you may encounter a :exc:`RuntimeError` exception with the message ``maximum recursion limit`` exceeded. For example, :: - >>> import re >>> s = 'Begin ' + 1000*'a very long string ' + 'end' >>> re.match('Begin (\w| )*? end', s).end() Traceback (most recent call last): @@ -1042,28 +1046,30 @@ search() vs. match() In a nutshell, :func:`match` only attempts to match a pattern at the beginning of a string where :func:`search` will match a pattern anywhere in a string. -For example:: +For example: >>> re.match("o", "dog") # No match as "o" is not the first letter of "dog". >>> re.search("o", "dog") # Match as search() looks everywhere in the string. - <_sre.SRE_Match object at 0x827e9f8> + <_sre.SRE_Match object at ...> .. note:: - The following applies only to regular expression objects like those created - with ``re.compile("pattern")``, not the primitives - ``re.match(pattern, string)`` or ``re.search(pattern, string)``. + The following applies only to regular expression objects like those created + with ``re.compile("pattern")``, not the primitives ``re.match(pattern, + string)`` or ``re.search(pattern, string)``. :func:`match` has an optional second parameter that gives an index in the string -where the search is to start:: +where the search is to start: >>> pattern = re.compile("o") >>> pattern.match("dog") # No match as "o" is not at the start of "dog." + # Equivalent to the above expression as 0 is the default starting index: >>> pattern.match("dog", 0) + # Match as "o" is the 2nd character of "dog" (index 0 is the first): >>> pattern.match("dog", 1) - <_sre.SRE_Match object at 0x827eb10> + <_sre.SRE_Match object at ...> >>> pattern.match("dog", 2) # No match as "o" is not the 3rd character of "dog." @@ -1076,29 +1082,35 @@ easily read and modified by Python as demonstrated in the following example that creates a phonebook. First, here is the input. Normally it may come from a file, here we are using -triple-quoted string syntax:: +triple-quoted string syntax: >>> input = """Ross McFluff: 834.345.1254 155 Elm Street - - Ronald Heathmore: 892.345.3428 436 Finley Avenue - Frank Burger: 925.541.7625 662 South Dogwood Way - - - Heather Albrecht: 548.326.4584 919 Park Place""" + ... + ... Ronald Heathmore: 892.345.3428 436 Finley Avenue + ... Frank Burger: 925.541.7625 662 South Dogwood Way + ... + ... + ... Heather Albrecht: 548.326.4584 919 Park Place""" The entries are separated by one or more newlines. Now we convert the string -into a list with each nonempty line having its own entry:: +into a list with each nonempty line having its own entry: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE >>> entries = re.split("\n+", input) >>> entries - ['Ross McFluff 834.345.1254 155 Elm Street', - 'Ronald Heathmore 892.345.3428 436 Finley Avenue', - 'Frank Burger 925.541.7625 662 South Dogwood Way', - 'Heather Albrecht 548.326.4584 919 Park Place'] + ['Ross McFluff: 834.345.1254 155 Elm Street', + 'Ronald Heathmore: 892.345.3428 436 Finley Avenue', + 'Frank Burger: 925.541.7625 662 South Dogwood Way', + 'Heather Albrecht: 548.326.4584 919 Park Place'] Finally, split each entry into a list with first name, last name, telephone number, and address. We use the ``maxsplit`` parameter of :func:`split` -because the address has spaces, our splitting pattern, in it:: +because the address has spaces, our splitting pattern, in it: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE >>> [re.split(":? ", entry, 3) for entry in entries] [['Ross', 'McFluff', '834.345.1254', '155 Elm Street'], @@ -1108,7 +1120,10 @@ because the address has spaces, our splitting pattern, in it:: The ``:?`` pattern matches the colon after the last name, so that it does not occur in the result list. With a ``maxsplit`` of ``4``, we could separate the -house number from the street name:: +house number from the street name: + +.. doctest:: + :options: +NORMALIZE_WHITESPACE >>> [re.split(":? ", entry, 4) for entry in entries] [['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'], @@ -1142,7 +1157,7 @@ Finding all Adverbs :func:`findall` matches *all* occurrences of a pattern, not just the first one as :func:`search` does. For example, if one was a writer and wanted to find all of the adverbs in some text, he or she might use :func:`findall` in -the following manner:: +the following manner: >>> text = "He was carefully disguised but captured quickly by police." >>> re.findall(r"\w+ly", text) @@ -1156,11 +1171,11 @@ If one wants more information about all matches of a pattern than the matched text, :func:`finditer` is useful as it provides instances of :class:`MatchObject` instead of strings. Continuing with the previous example, if one was a writer who wanted to find all of the adverbs *and their positions* -in some text, he or she would use :func:`finditer` in the following manner:: +in some text, he or she would use :func:`finditer` in the following manner: >>> text = "He was carefully disguised but captured quickly by police." >>> for m in re.finditer(r"\w+ly", text): - print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0))) + ... print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0))) 07-16: carefully 40-47: quickly @@ -1171,19 +1186,19 @@ Raw String Notation Raw string notation (``r"text"``) keeps regular expressions sane. Without it, every backslash (``'\'``) in a regular expression would have to be prefixed with another one to escape it. For example, the two following lines of code are -functionally identical:: +functionally identical: >>> re.match(r"\W(.)\1\W", " ff ") - <_sre.SRE_Match object at 0x8262760> + <_sre.SRE_Match object at ...> >>> re.match("\\W(.)\\1\\W", " ff ") - <_sre.SRE_Match object at 0x82627a0> + <_sre.SRE_Match object at ...> When one wants to match a literal backslash, it must be escaped in the regular expression. With raw string notation, this means ``r"\\"``. Without raw string notation, one must use ``"\\\\"``, making the following lines of code -functionally identical:: +functionally identical: >>> re.match(r"\\", r"\\") - <_sre.SRE_Match object at 0x827eb48> + <_sre.SRE_Match object at ...> >>> re.match("\\\\", r"\\") - <_sre.SRE_Match object at 0x827ec60> + <_sre.SRE_Match object at ...> diff --git a/Doc/library/sched.rst b/Doc/library/sched.rst index 5dfa456..70e1d85 100644 --- a/Doc/library/sched.rst +++ b/Doc/library/sched.rst @@ -25,7 +25,7 @@ scheduler: Example:: >>> 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_some_times(): diff --git a/Doc/library/select.rst b/Doc/library/select.rst index 1368c78..df3ea9f 100644 --- a/Doc/library/select.rst +++ b/Doc/library/select.rst @@ -24,12 +24,12 @@ The module defines the following: string, as would be printed by the C function :cfunc:`perror`. -.. type:: epoll([sizehint=-1]) +.. function:: epoll([sizehint=-1]) - (Only supported on Linux 2.5.44 and newer.) Returns an edge polling - object, which can be used as Edge or Level Triggered interface for I/O - events; see section :ref:`epoll-objects` below for the methods supported - by epolling objects. + (Only supported on Linux 2.5.44 and newer.) Returns an edge polling object, + which can be used as Edge or Level Triggered interface for I/O events; see + section :ref:`epoll-objects` below for the methods supported by epolling + objects. .. versionadded:: 2.6 @@ -42,20 +42,18 @@ The module defines the following: by polling objects. -.. type:: kqueue() +.. function:: kqueue() - (Only supported on BSD.) Returns a kernel queue object - object; see section :ref:`kqueue-objects` below for the methods supported - by kqueue objects. + (Only supported on BSD.) Returns a kernel queue object object; see section + :ref:`kqueue-objects` below for the methods supported by kqueue objects. .. versionadded:: 2.6 -.. type:: kqueue(ident, filter=KQ_FILTER_READ, flags=KQ_ADD, fflags=0, data=0, udata=0) +.. function:: kqueue(ident, filter=KQ_FILTER_READ, flags=KQ_ADD, fflags=0, data=0, udata=0) - (Only supported on BSD.) Returns a kernel event object - object; see section :ref:`kevent-objects` below for the methods supported - by kqueue objects. + (Only supported on BSD.) Returns a kernel event object object; see section + :ref:`kevent-objects` below for the methods supported by kqueue objects. .. versionadded:: 2.6 @@ -287,16 +285,16 @@ Kqueue Objects Kevent Objects -------------- - http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2 +http://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2 - .. attribute:: ident +.. attribute:: kevent.ident Value used to identify the event. The interpretation depends on the filter but it's usually the file descriptor. In the constructor ident can either be an int or an object with a fileno() function. kevent stores the integer internally. - .. attribute:: filter +.. attribute:: kevent.filter Name of the kernel filter @@ -325,7 +323,7 @@ Kevent Objects | :const:`KQ_FILTER_TIMER` | Establishes an arbitrary timer | +---------------------------+---------------------------------------------+ - .. attribute:: flags +.. attribute:: kevent.flags Filter action @@ -354,12 +352,12 @@ Kevent Objects +---------------------------+---------------------------------------------+ - .. attribute:: fflags +.. attribute:: kevent.fflags Filter specific flags - *:const:`KQ_FILTER_READ` and :const:`KQ_FILTER_WRITE` filter flags + *:const:`KQ_FILTER_READ` and :const:`KQ_FILTER_WRITE` filter flags* +----------------------------+--------------------------------------------+ | Constant | Meaning | @@ -425,11 +423,11 @@ Kevent Objects +----------------------------+--------------------------------------------+ - .. attribute:: data +.. attribute:: kevent.data Filter specific data - .. attribute:: udata +.. attribute:: kevent.udata User defined value diff --git a/Doc/library/stdtypes.rst b/Doc/library/stdtypes.rst index 18131b9..5213598 100644 --- a/Doc/library/stdtypes.rst +++ b/Doc/library/stdtypes.rst @@ -601,7 +601,7 @@ Notes: 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; nested structures are not copied. This often haunts new Python programmers; - consider:: + consider: >>> lists = [[]] * 3 >>> lists @@ -611,9 +611,9 @@ Notes: [[3], [3], [3]] 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. Modifying any of the elements of ``lists`` modifies this single - list. You can create a list of different lists this way:: + 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. + You can create a list of different lists this way: >>> lists = [[] for i in range(3)] >>> lists[0].append(3) @@ -819,7 +819,7 @@ functions based on regular expressions. 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 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 ' @@ -899,7 +899,7 @@ functions based on regular expressions. 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 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' @@ -953,7 +953,7 @@ functions based on regular expressions. 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. The *chars* argument is not a prefix or suffix; rather, all combinations of its - values are stripped:: + values are stripped: >>> ' spacious '.strip() 'spacious' @@ -983,6 +983,10 @@ functions based on regular expressions. A *map* for :meth:`translate` is usually best created by :meth:`str.maketrans`. + 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 + ``None`` for translations that only delete characters: + .. note:: An even more flexible approach is to create a custom character mapping @@ -1079,10 +1083,11 @@ components, which must occur in this order: 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 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.' % - {'language': "Python", "#": 2}) + >>> print('%(language)s has %(#)03d quote types.' % \ + ... {'language': "Python", "#": 2}) Python has 002 quote types. In this case no ``*`` specifiers may occur in a format (since they require a diff --git a/Doc/library/string.rst b/Doc/library/string.rst index ce5129d..b5fa4f7 100644 --- a/Doc/library/string.rst +++ b/Doc/library/string.rst @@ -484,7 +484,7 @@ these rules. The methods of :class:`Template` are: 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. -Here is an example of how to use a Template:: +Here is an example of how to use a Template: >>> from string import Template >>> s = Template('$who likes $what') diff --git a/Doc/library/time.rst b/Doc/library/time.rst index 1907011..ea164d3 100644 --- a/Doc/library/time.rst +++ b/Doc/library/time.rst @@ -350,11 +350,12 @@ The module defines the following functions and data items: 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)``. - For example:: + For example: >>> import time - >>> time.strptime("30 Nov 00", "%d %b %y") - (2000, 11, 30, 0, 0, 0, 3, 335, -1) + >>> time.strptime("30 Nov 00", "%d %b %y") # doctest: +NORMALIZE_WHITESPACE + 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`` and whether ``daylight`` is true. Because of this, it is platform-specific diff --git a/Doc/library/unicodedata.rst b/Doc/library/unicodedata.rst index 7a779f6..e6e6d1a 100644 --- a/Doc/library/unicodedata.rst +++ b/Doc/library/unicodedata.rst @@ -142,8 +142,9 @@ In addition, the module exposes the following constant: Unicode database version 3.2 instead, for applications that require this specific version of the Unicode database (such as IDNA). -Examples:: +Examples: + >>> import unicodedata >>> unicodedata.lookup('LEFT CURLY BRACKET') u'{' >>> unicodedata.name('/') diff --git a/Doc/library/urlparse.rst b/Doc/library/urlparse.rst index 1c095ae..e305e0b 100644 --- a/Doc/library/urlparse.rst +++ b/Doc/library/urlparse.rst @@ -35,12 +35,13 @@ The :mod:`urlparse` module defines the following functions: 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 result, except for a leading slash in the *path* component, which is retained if - present. For example:: + present. For example: >>> from urlparse import urlparse >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html') - >>> o - ('http', 'www.cwi.nl:80', '/%7Eguido/Python.html', '', '', '') + >>> o # doctest: +NORMALIZE_WHITESPACE + ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html', + params='', query='', fragment='') >>> o.scheme 'http' >>> o.port @@ -151,7 +152,7 @@ The :mod:`urlparse` module defines the following functions: Construct a full ("absolute") URL by combining a "base URL" (*base*) with another URL (*url*). Informally, this uses components of the base URL, in 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 >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html') @@ -165,7 +166,7 @@ The :mod:`urlparse` module defines the following functions: 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: - :: + .. doctest:: >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', ... '//www.python.org/%7Eguido') @@ -216,7 +217,7 @@ described in those functions, as well as provide an additional method: and fragment identifiers will be removed. The result of this method is a fixpoint if passed back through the original - parsing function:: + parsing function: >>> import urlparse >>> url = 'HTTP://www.Python.org/doc/#' diff --git a/Doc/library/weakref.rst b/Doc/library/weakref.rst index 83e6000..bffa2ba 100644 --- a/Doc/library/weakref.rst +++ b/Doc/library/weakref.rst @@ -24,18 +24,20 @@ only remaining references to a referent are weak references, :term:`garbage collection` is free to destroy the referent and reuse its memory for something else. A primary use for weak references is to implement caches or mappings holding large objects, where it's desired that a large object not be -kept alive solely because it appears in a cache or mapping. For example, if you -have a number of large binary image objects, you may wish to associate a name -with each. If you used a Python dictionary to map names to images, or images to -names, the image objects would remain alive just because they appeared as values -or keys in the dictionaries. The :class:`WeakKeyDictionary` and -:class:`WeakValueDictionary` classes supplied by the :mod:`weakref` module are -an alternative, using weak references to construct mappings that don't keep -objects alive solely because they appear in the mapping objects. If, for -example, an image object is a value in a :class:`WeakValueDictionary`, then when -the last remaining references to that image object are the weak references held -by weak mappings, garbage collection can reclaim the object, and its -corresponding entries in weak mappings are simply deleted. +kept alive solely because it appears in a cache or mapping. + +For example, if you have a number of large binary image objects, you may wish to +associate a name with each. If you used a Python dictionary to map names to +images, or images to names, the image objects would remain alive just because +they appeared as values or keys in the dictionaries. The +:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by +the :mod:`weakref` module are an alternative, using weak references to construct +mappings that don't keep objects alive solely because they appear in the mapping +objects. If, for example, an image object is a value in a +:class:`WeakValueDictionary`, then when the last remaining references to that +image object are the weak references held by weak mappings, garbage collection +can reclaim the object, and its corresponding entries in weak mappings are +simply deleted. :class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references in their implementation, setting up callback functions on the weak references @@ -49,6 +51,12 @@ they need -- it's not usually necessary to create your own weak references directly. The low-level machinery used by the weak dictionary implementations is exposed by the :mod:`weakref` module for the benefit of advanced uses. +.. note:: + + Weak references to an object are cleared before the object's :meth:`__del__` + is called, to ensure that the weak reference callback (if any) finds the + object still alive. + Not all objects can be weakly referenced; those objects which can include class instances, functions written in Python (but not in C), instance methods, sets, frozensets, file objects, :term:`generator`\s, type objects, :class:`DBcursor` @@ -130,11 +138,11 @@ Extension types can easily be made to support weak references; see .. note:: - Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python + Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python dictionary, it must not change size when iterating over it. This can be - difficult to ensure for a :class:`WeakKeyDictionary` because actions performed - by the program during iteration may cause items in the dictionary to vanish "by - magic" (as a side effect of garbage collection). + difficult to ensure for a :class:`WeakKeyDictionary` because actions + performed by the program during iteration may cause items in the + dictionary to vanish "by magic" (as a side effect of garbage collection). :class:`WeakKeyDictionary` objects have the following additional methods. These expose the internal references directly. The references are not guaranteed to @@ -229,7 +237,7 @@ Weak Reference Objects ---------------------- 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 >>> class Object: @@ -242,7 +250,7 @@ to be obtained, if it still exists, by calling it:: True If the referent no longer exists, calling the reference object returns -:const:`None`:: +:const:`None`: >>> del o, o2 >>> print(r()) |