Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
15 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Doc/tutorial/classes.rst

    r2 r391  
    55*******
    66
    7 Python's class mechanism adds classes to the language with a minimum of new
    8 syntax and semantics.  It is a mixture of the class mechanisms found in C++ and
    9 Modula-3.  As is true for modules, classes in Python do not put an absolute
    10 barrier between definition and user, but rather rely on the politeness of the
    11 user not to "break into the definition."  The most important features of classes
    12 are retained with full power, however: the class inheritance mechanism allows
     7Compared with other programming languages, Python's class mechanism adds classes
     8with a minimum of new syntax and semantics.  It is a mixture of the class
     9mechanisms found in C++ and Modula-3.  Python classes provide all the standard
     10features of Object Oriented Programming: the class inheritance mechanism allows
    1311multiple base classes, a derived class can override any methods of its base
    1412class or classes, and a method can call the method of a base class with the same
    15 name.  Objects can contain an arbitrary amount of data.
    16 
    17 In C++ terminology, all class members (including the data members) are *public*,
    18 and all member functions are *virtual*.  As in Modula-3, there are no shorthands
    19 for referencing the object's members from its methods: the method function is
    20 declared with an explicit first argument representing the object, which is
    21 provided implicitly by the call.  As in Smalltalk, classes themselves are
    22 objects.  This provides semantics for importing and renaming.  Unlike C++ and
    23 Modula-3, built-in types can be used as base classes for extension by the user.
    24 Also, like in C++, most built-in operators with special syntax (arithmetic
    25 operators, subscripting etc.) can be redefined for class instances.
     13name.  Objects can contain arbitrary amounts and kinds of data.  As is true for
     14modules, classes partake of the dynamic nature of Python: they are created at
     15runtime, and can be modified further after creation.
     16
     17In C++ terminology, normally class members (including the data members) are
     18*public* (except see below :ref:`tut-private`), and all member functions are
     19*virtual*.  As in Modula-3, there are no shorthands for referencing the object's
     20members from its methods: the method function is declared with an explicit first
     21argument representing the object, which is provided implicitly by the call.  As
     22in Smalltalk, classes themselves are objects.  This provides semantics for
     23importing and renaming.  Unlike C++ and Modula-3, built-in types can be used as
     24base classes for extension by the user.  Also, like in C++, most built-in
     25operators with special syntax (arithmetic operators, subscripting etc.) can be
     26redefined for class instances.
    2627
    2728(Lacking universally accepted terminology to talk about classes, I will make
     
    6566implemented as Python dictionaries, but that's normally not noticeable in any
    6667way (except for performance), and it may change in the future.  Examples of
    67 namespaces are: the set of built-in names (functions such as :func:`abs`, and
     68namespaces are: the set of built-in names (containing functions such as :func:`abs`, and
    6869built-in exception names); the global names in a module; and the local names in
    6970a function invocation.  In a sense the set of attributes of an object also form
     
    409410
    410411Methods may reference global names in the same way as ordinary functions.  The
    411 global scope associated with a method is the module containing the class
    412 definition.  (The class itself is never used as a global scope.)  While one
     412global scope associated with a method is the module containing its
     413definition.  (A class is never used as a global scope.)  While one
    413414rarely encounters a good reason for using global data in a method, there are
    414415many legitimate uses of the global scope: for one thing, functions and modules
     
    518519
    519520With new-style classes, dynamic ordering is necessary because all  cases of
    520 multiple inheritance exhibit one or more diamond relationships (where one at
     521multiple inheritance exhibit one or more diamond relationships (where at
    521522least one of the parent classes can be accessed through multiple paths from the
    522523bottommost class).  For example, all new-style classes inherit from
     
    534535.. _tut-private:
    535536
    536 Private Variables
    537 =================
     537Private Variables and Class-local References
     538============================================
    538539
    539540"Private" instance variables that cannot be accessed except from inside an
    540 object, don't exist in Python.  However, there is a convention that is followed
     541object don't exist in Python.  However, there is a convention that is followed
    541542by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should
    542543be treated as a non-public part of the API (whether it is a function, a method
     
    553554occurs within the definition of a class.
    554555
     556Name mangling is helpful for letting subclasses override methods without
     557breaking intraclass method calls.  For example::
     558
     559   class Mapping:
     560       def __init__(self, iterable):
     561           self.items_list = []
     562           self.__update(iterable)
     563
     564       def update(self, iterable):
     565           for item in iterable:
     566               self.items_list.append(item)
     567
     568       __update = update   # private copy of original update() method
     569
     570   class MappingSubclass(Mapping):
     571
     572       def update(self, keys, values):
     573           # provides new signature for update()
     574           # but does not break __init__()
     575           for item in zip(keys, values):
     576               self.items_list.append(item)
     577
    555578Note that the mangling rules are designed mostly to avoid accidents; it still is
    556579possible to access or modify a variable that is considered private.  This can
     
    587610passed a class that emulates the methods of that data type instead.  For
    588611instance, if you have a function that formats some data from a file object, you
    589 can define a class with methods :meth:`read` and :meth:`readline` that get the
     612can define a class with methods :meth:`read` and :meth:`!readline` that get the
    590613data from a string buffer instead, and pass it as an argument.
    591614
     
    666689       print char
    667690   for line in open("myfile.txt"):
    668        print line
     691       print line,
    669692
    670693This style of access is clear, concise, and convenient.  The use of iterators
    671694pervades and unifies Python.  Behind the scenes, the :keyword:`for` statement
    672695calls :func:`iter` on the container object.  The function returns an iterator
    673 object that defines the method :meth:`next` which accesses elements in the
    674 container one at a time.  When there are no more elements, :meth:`next` raises a
    675 :exc:`StopIteration` exception which tells the :keyword:`for` loop to terminate.
     696object that defines the method :meth:`~iterator.next` which accesses elements
     697in the container one at a time.  When there are no more elements,
     698:meth:`~iterator.next` raises a :exc:`StopIteration` exception which tells the
     699:keyword:`for` loop to terminate.
    676700This example shows how it all works::
    677701
     
    687711   'c'
    688712   >>> it.next()
    689 
    690713   Traceback (most recent call last):
    691714     File "<stdin>", line 1, in ?
     
    694717
    695718Having seen the mechanics behind the iterator protocol, it is easy to add
    696 iterator behavior to your classes.  Define a :meth:`__iter__` method which
     719iterator behavior to your classes.  Define an :meth:`__iter__` method which
    697720returns an object with a :meth:`next` method.  If the class defines
    698721:meth:`next`, then :meth:`__iter__` can just return ``self``::
    699722
    700723   class Reverse:
    701        "Iterator for looping over a sequence backwards"
     724       """Iterator for looping over a sequence backwards."""
    702725       def __init__(self, data):
    703726           self.data = data
     
    711734           return self.data[self.index]
    712735
    713    >>> for char in Reverse('spam'):
     736::
     737
     738   >>> rev = Reverse('spam')
     739   >>> iter(rev)
     740   <__main__.Reverse object at 0x00A1DB50>
     741   >>> for char in rev:
    714742   ...     print char
    715743   ...
     
    735763       for index in range(len(data)-1, -1, -1):
    736764           yield data[index]
     765
     766::
    737767
    738768   >>> for char in reverse('golf'):
  • python/trunk/Doc/tutorial/controlflow.rst

    r2 r391  
    6060
    6161   >>> # Measure some strings:
    62    ... a = ['cat', 'window', 'defenestrate']
    63    >>> for x in a:
    64    ...     print x, len(x)
     62   ... words = ['cat', 'window', 'defenestrate']
     63   >>> for w in words:
     64   ...     print w, len(w)
    6565   ...
    6666   cat 3
     
    6868   defenestrate 12
    6969
    70 It is not safe to modify the sequence being iterated over in the loop (this can
    71 only happen for mutable sequence types, such as lists).  If you need to modify
    72 the list you are iterating over (for example, to duplicate selected items) you
    73 must iterate over a copy.  The slice notation makes this particularly
    74 convenient::
    75 
    76    >>> for x in a[:]: # make a slice copy of the entire list
    77    ...    if len(x) > 6: a.insert(0, x)
    78    ...
    79    >>> a
     70If you need to modify the sequence you are iterating over while inside the loop
     71(for example to duplicate selected items), it is recommended that you first
     72make a copy.  Iterating over a sequence does not implicitly make a copy.  The
     73slice notation makes this especially convenient::
     74
     75   >>> for w in words[:]:  # Loop over a slice copy of the entire list.
     76   ...     if len(w) > 6:
     77   ...         words.insert(0, w)
     78   ...
     79   >>> words
    8080   ['defenestrate', 'cat', 'window', 'defenestrate']
    8181
     
    129129The :keyword:`break` statement, like in C, breaks out of the smallest enclosing
    130130:keyword:`for` or :keyword:`while` loop.
    131 
    132 The :keyword:`continue` statement, also borrowed from C, continues with the next
    133 iteration of the loop.
    134131
    135132Loop statements may have an ``else`` clause; it is executed when the loop
     
    156153   8 equals 2 * 4
    157154   9 equals 3 * 3
     155
     156(Yes, this is the correct code.  Look closely: the ``else`` clause belongs to
     157the :keyword:`for` loop, **not** the :keyword:`if` statement.)
     158
     159When used with a loop, the ``else`` clause has more in common with the
     160``else`` clause of a :keyword:`try` statement than it does that of
     161:keyword:`if` statements: a :keyword:`try` statement's ``else`` clause runs
     162when no exception occurs, and a loop's ``else`` clause runs when no ``break``
     163occurs. For more on the :keyword:`try` statement and exceptions, see
     164:ref:`tut-handling`.
     165
     166The :keyword:`continue` statement, also borrowed from C, continues with the next
     167iteration of the loop::
     168
     169    >>> for num in range(2, 10):
     170    ...     if num % 2 == 0:
     171    ...         print "Found an even number", num
     172    ...         continue
     173    ...     print "Found a number", num
     174    Found an even number 2
     175    Found a number 3
     176    Found an even number 4
     177    Found a number 5
     178    Found an even number 6
     179    Found a number 7
     180    Found an even number 8
     181    Found a number 9
    158182
    159183
     
    381405-----------------
    382406
    383 Functions can also be called using keyword arguments of the form ``keyword =
    384 value``.  For instance, the following function::
     407Functions can also be called using :term:`keyword arguments <keyword argument>`
     408of the form ``kwarg=value``.  For instance, the following function::
    385409
    386410   def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
     
    390414       print "-- It's", state, "!"
    391415
    392 could be called in any of the following ways::
    393 
    394    parrot(1000)
    395    parrot(action = 'VOOOOOM', voltage = 1000000)
    396    parrot('a thousand', state = 'pushing up the daisies')
    397    parrot('a million', 'bereft of life', 'jump')
    398 
    399 but the following calls would all be invalid::
     416accepts one required argument (``voltage``) and three optional arguments
     417(``state``, ``action``, and ``type``).  This function can be called in any
     418of the following ways::
     419
     420   parrot(1000)                                          # 1 positional argument
     421   parrot(voltage=1000)                                  # 1 keyword argument
     422   parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
     423   parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
     424   parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
     425   parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword
     426
     427but all the following calls would be invalid::
    400428
    401429   parrot()                     # required argument missing
    402    parrot(voltage=5.0, 'dead')  # non-keyword argument following keyword
    403    parrot(110, voltage=220)     # duplicate value for argument
    404    parrot(actor='John Cleese')  # unknown keyword
    405 
    406 In general, an argument list must have any positional arguments followed by any
    407 keyword arguments, where the keywords must be chosen from the formal parameter
    408 names.  It's not important whether a formal parameter has a default value or
    409 not.  No argument may receive a value more than once --- formal parameter names
    410 corresponding to positional arguments cannot be used as keywords in the same
    411 calls. Here's an example that fails due to this restriction::
     430   parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument
     431   parrot(110, voltage=220)     # duplicate value for the same argument
     432   parrot(actor='John Cleese')  # unknown keyword argument
     433
     434In a function call, keyword arguments must follow positional arguments.
     435All the keyword arguments passed must match one of the arguments
     436accepted by the function (e.g. ``actor`` is not a valid argument for the
     437``parrot`` function), and their order is not important.  This also includes
     438non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too).
     439No argument may receive a value more than once.
     440Here's an example that fails due to this restriction::
    412441
    413442   >>> def function(a):
     
    430459       print "-- Do you have any", kind, "?"
    431460       print "-- I'm sorry, we're all out of", kind
    432        for arg in arguments: print arg
     461       for arg in arguments:
     462           print arg
    433463       print "-" * 40
    434        keys = keywords.keys()
    435        keys.sort()
    436        for kw in keys: print kw, ":", keywords[kw]
     464       keys = sorted(keywords.keys())
     465       for kw in keys:
     466           print kw, ":", keywords[kw]
    437467
    438468It could be called like this::
     
    455485   sketch : Cheese Shop Sketch
    456486
    457 Note that the :meth:`sort` method of the list of keyword argument names is
    458 called before printing the contents of the ``keywords`` dictionary; if this is
    459 not done, the order in which the arguments are printed is undefined.
    460 
     487Note that the list of keyword argument names is created by sorting the result
     488of the keywords dictionary's ``keys()`` method before printing its contents;
     489if this is not done, the order in which the arguments are printed is undefined.
    461490
    462491.. _tut-arbitraryargs:
     
    513542.. _tut-lambda:
    514543
    515 Lambda Forms
    516 ------------
    517 
    518 By popular demand, a few features commonly found in functional programming
    519 languages like Lisp have been added to Python.  With the :keyword:`lambda`
    520 keyword, small anonymous functions can be created. Here's a function that
    521 returns the sum of its two arguments: ``lambda a, b: a+b``.  Lambda forms can be
    522 used wherever function objects are required.  They are syntactically restricted
    523 to a single expression.  Semantically, they are just syntactic sugar for a
    524 normal function definition.  Like nested function definitions, lambda forms can
    525 reference variables from the containing scope::
     544Lambda Expressions
     545------------------
     546
     547Small anonymous functions can be created with the :keyword:`lambda` keyword.
     548This function returns the sum of its two arguments: ``lambda a, b: a+b``.
     549Lambda functions can be used wherever function objects are required.  They are
     550syntactically restricted to a single expression.  Semantically, they are just
     551syntactic sugar for a normal function definition.  Like nested function
     552definitions, lambda functions can reference variables from the containing
     553scope::
    526554
    527555   >>> def make_incrementor(n):
     
    533561   >>> f(1)
    534562   43
     563
     564The above example uses a lambda expression to return a function.  Another use
     565is to pass a small function as an argument::
     566
     567   >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
     568   >>> pairs.sort(key=lambda pair: pair[1])
     569   >>> pairs
     570   [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
    535571
    536572
  • python/trunk/Doc/tutorial/datastructures.rst

    r2 r391  
    171171the sequence for which ``function(item)`` is true. If *sequence* is a
    172172:class:`string` or :class:`tuple`, the result will be of the same type;
    173 otherwise, it is always a :class:`list`. For example, to compute some primes::
     173otherwise, it is always a :class:`list`. For example, to compute a sequence of
     174numbers not divisible by 2 or 3::
    174175
    175176   >>> def f(x): return x % 2 != 0 and x % 3 != 0
     
    229230and works exactly like this.
    230231
    231 .. versionadded:: 2.3
    232 
     232.. _tut-listcomps:
    233233
    234234List Comprehensions
    235235-------------------
    236236
    237 List comprehensions provide a concise way to create lists without resorting to
    238 use of :func:`map`, :func:`filter` and/or :keyword:`lambda`. The resulting list
    239 definition tends often to be clearer than lists built using those constructs.
    240 Each list comprehension consists of an expression followed by a :keyword:`for`
    241 clause, then zero or more :keyword:`for` or :keyword:`if` clauses.  The result
    242 will be a list resulting from evaluating the expression in the context of the
    243 :keyword:`for` and :keyword:`if` clauses which follow it.  If the expression
    244 would evaluate to a tuple, it must be parenthesized. ::
    245 
     237List comprehensions provide a concise way to create lists.
     238Common applications are to make new lists where each element is the result of
     239some operations applied to each member of another sequence or iterable, or to
     240create a subsequence of those elements that satisfy a certain condition.
     241
     242For example, assume we want to create a list of squares, like::
     243
     244   >>> squares = []
     245   >>> for x in range(10):
     246   ...     squares.append(x**2)
     247   ...
     248   >>> squares
     249   [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
     250
     251We can obtain the same result with::
     252
     253   squares = [x**2 for x in range(10)]
     254
     255This is also equivalent to ``squares = map(lambda x: x**2, range(10))``,
     256but it's more concise and readable.
     257
     258A list comprehension consists of brackets containing an expression followed
     259by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
     260clauses.  The result will be a new list resulting from evaluating the expression
     261in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
     262For example, this listcomp combines the elements of two lists if they are not
     263equal::
     264
     265   >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
     266   [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
     267
     268and it's equivalent to:
     269
     270   >>> combs = []
     271   >>> for x in [1,2,3]:
     272   ...     for y in [3,1,4]:
     273   ...         if x != y:
     274   ...             combs.append((x, y))
     275   ...
     276   >>> combs
     277   [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
     278
     279Note how the order of the :keyword:`for` and :keyword:`if` statements is the
     280same in both these snippets.
     281
     282If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
     283it must be parenthesized. ::
     284
     285   >>> vec = [-4, -2, 0, 2, 4]
     286   >>> # create a new list with the values doubled
     287   >>> [x*2 for x in vec]
     288   [-8, -4, 0, 4, 8]
     289   >>> # filter the list to exclude negative numbers
     290   >>> [x for x in vec if x >= 0]
     291   [0, 2, 4]
     292   >>> # apply a function to all the elements
     293   >>> [abs(x) for x in vec]
     294   [4, 2, 0, 2, 4]
     295   >>> # call a method on each element
    246296   >>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
    247297   >>> [weapon.strip() for weapon in freshfruit]
    248298   ['banana', 'loganberry', 'passion fruit']
    249    >>> vec = [2, 4, 6]
    250    >>> [3*x for x in vec]
    251    [6, 12, 18]
    252    >>> [3*x for x in vec if x > 3]
    253    [12, 18]
    254    >>> [3*x for x in vec if x < 2]
    255    []
    256    >>> [[x,x**2] for x in vec]
    257    [[2, 4], [4, 16], [6, 36]]
    258    >>> [x, x**2 for x in vec]  # error - parens required for tuples
    259      File "<stdin>", line 1, in ?
    260        [x, x**2 for x in vec]
     299   >>> # create a list of 2-tuples like (number, square)
     300   >>> [(x, x**2) for x in range(6)]
     301   [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
     302   >>> # the tuple must be parenthesized, otherwise an error is raised
     303   >>> [x, x**2 for x in range(6)]
     304     File "<stdin>", line 1
     305       [x, x**2 for x in range(6)]
    261306                  ^
    262307   SyntaxError: invalid syntax
    263    >>> [(x, x**2) for x in vec]
    264    [(2, 4), (4, 16), (6, 36)]
    265    >>> vec1 = [2, 4, 6]
    266    >>> vec2 = [4, 3, -9]
    267    >>> [x*y for x in vec1 for y in vec2]
    268    [8, 6, -18, 16, 12, -36, 24, 18, -54]
    269    >>> [x+y for x in vec1 for y in vec2]
    270    [6, 5, -7, 8, 7, -5, 10, 9, -3]
    271    >>> [vec1[i]*vec2[i] for i in range(len(vec1))]
    272    [8, 12, -54]
    273 
    274 List comprehensions are much more flexible than :func:`map` and can be applied
    275 to complex expressions and nested functions::
    276 
    277    >>> [str(round(355/113.0, i)) for i in range(1,6)]
     308   >>> # flatten a list using a listcomp with two 'for'
     309   >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
     310   >>> [num for elem in vec for num in elem]
     311   [1, 2, 3, 4, 5, 6, 7, 8, 9]
     312
     313List comprehensions can contain complex expressions and nested functions::
     314
     315   >>> from math import pi
     316   >>> [str(round(pi, i)) for i in range(1, 6)]
    278317   ['3.1', '3.14', '3.142', '3.1416', '3.14159']
    279318
    280319
    281320Nested List Comprehensions
    282 --------------------------
    283 
    284 If you've got the stomach for it, list comprehensions can be nested. They are a
    285 powerful tool but -- like all powerful tools -- they need to be used carefully,
    286 if at all.
    287 
    288 Consider the following example of a 3x3 matrix held as a list containing three
    289 lists, one list per row::
    290 
    291     >>> mat = [
    292     ...        [1, 2, 3],
    293     ...        [4, 5, 6],
    294     ...        [7, 8, 9],
    295     ...       ]
    296 
    297 Now, if you wanted to swap rows and columns, you could use a list
    298 comprehension::
    299 
    300     >>> print [[row[i] for row in mat] for i in [0, 1, 2]]
    301     [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
    302 
    303 Special care has to be taken for the *nested* list comprehension:
    304 
    305     To avoid apprehension when nesting list comprehensions, read from right to
    306     left.
    307 
    308 A more verbose version of this snippet shows the flow explicitly::
    309 
    310     for i in [0, 1, 2]:
    311         for row in mat:
    312             print row[i],
    313         print
    314 
    315 In real world, you should prefer built-in functions to complex flow statements.
     321''''''''''''''''''''''''''
     322
     323The initial expression in a list comprehension can be any arbitrary expression,
     324including another list comprehension.
     325
     326Consider the following example of a 3x4 matrix implemented as a list of
     3273 lists of length 4::
     328
     329   >>> matrix = [
     330   ...     [1, 2, 3, 4],
     331   ...     [5, 6, 7, 8],
     332   ...     [9, 10, 11, 12],
     333   ... ]
     334
     335The following list comprehension will transpose rows and columns::
     336
     337   >>> [[row[i] for row in matrix] for i in range(4)]
     338   [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
     339
     340As we saw in the previous section, the nested listcomp is evaluated in
     341the context of the :keyword:`for` that follows it, so this example is
     342equivalent to::
     343
     344   >>> transposed = []
     345   >>> for i in range(4):
     346   ...     transposed.append([row[i] for row in matrix])
     347   ...
     348   >>> transposed
     349   [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
     350
     351which, in turn, is the same as::
     352
     353   >>> transposed = []
     354   >>> for i in range(4):
     355   ...     # the following 3 lines implement the nested listcomp
     356   ...     transposed_row = []
     357   ...     for row in matrix:
     358   ...         transposed_row.append(row[i])
     359   ...     transposed.append(transposed_row)
     360   ...
     361   >>> transposed
     362   [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
     363
     364
     365In the real world, you should prefer built-in functions to complex flow statements.
    316366The :func:`zip` function would do a great job for this use case::
    317367
    318     >>> zip(*mat)
    319     [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
     368   >>> zip(*matrix)
     369   [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
    320370
    321371See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
     
    373423   >>> u
    374424   ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
     425   >>> # Tuples are immutable:
     426   ... t[0] = 88888
     427   Traceback (most recent call last):
     428     File "<stdin>", line 1, in <module>
     429   TypeError: 'tuple' object does not support item assignment
     430   >>> # but they can contain mutable objects:
     431   ... v = ([1, 2, 3], [3, 2, 1])
     432   >>> v
     433   ([1, 2, 3], [3, 2, 1])
     434
    375435
    376436As you see, on output tuples are always enclosed in parentheses, so that nested
    377437tuples are interpreted correctly; they may be input with or without surrounding
    378438parentheses, although often parentheses are necessary anyway (if the tuple is
    379 part of a larger expression).
    380 
    381 Tuples have many uses.  For example: (x, y) coordinate pairs, employee records
    382 from a database, etc.  Tuples, like strings, are immutable: it is not possible
    383 to assign to the individual items of a tuple (you can simulate much of the same
    384 effect with slicing and concatenation, though).  It is also possible to create
    385 tuples which contain mutable objects, such as lists.
     439part of a larger expression).  It is not possible to assign to the individual
     440items of a tuple, however it is possible to create tuples which contain mutable
     441objects, such as lists.
     442
     443Though tuples may seem similar to lists, they are often used in different
     444situations and for different purposes.
     445Tuples are :term:`immutable`, and usually contain an heterogeneous sequence of
     446elements that are accessed via unpacking (see later in this section) or indexing
     447(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
     448Lists are :term:`mutable`, and their elements are usually homogeneous and are
     449accessed by iterating over the list.
    386450
    387451A special problem is the construction of tuples containing 0 or 1 items: the
     
    412476packing and sequence unpacking.
    413477
    414 .. XXX Add a bit on the difference between tuples and lists.
    415 
    416478
    417479.. _tut-sets:
     
    424486eliminating duplicate entries.  Set objects also support mathematical operations
    425487like union, intersection, difference, and symmetric difference.
     488
     489Curly braces or the :func:`set` function can be used to create sets.  Note: to
     490create an empty set you have to use ``set()``, not ``{}``; the latter creates an
     491empty dictionary, a data structure that we discuss in the next section.
    426492
    427493Here is a brief demonstration::
     
    451517   set(['r', 'd', 'b', 'm', 'z', 'l'])
    452518
     519Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions
     520are also supported::
     521
     522   >>> a = {x for x in 'abracadabra' if x not in 'abc'}
     523   >>> a
     524   set(['r', 'd'])
     525
    453526
    454527.. _tut-dictionaries:
     
    482555The :meth:`keys` method of a dictionary object returns a list of all the keys
    483556used in the dictionary, in arbitrary order (if you want it sorted, just apply
    484 the :meth:`sort` method to the list of keys).  To check whether a single key is
    485 in the dictionary, use the :keyword:`in` keyword.
     557the :func:`sorted` function to it).  To check whether a single key is in the
     558dictionary, use the :keyword:`in` keyword.
    486559
    487560Here is a small example using a dictionary::
     
    502575   True
    503576
    504 The :func:`dict` constructor builds dictionaries directly from lists of
    505 key-value pairs stored as tuples.  When the pairs form a pattern, list
    506 comprehensions can compactly specify the key-value list. ::
     577The :func:`dict` constructor builds dictionaries directly from sequences of
     578key-value pairs::
    507579
    508580   >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
    509581   {'sape': 4139, 'jack': 4098, 'guido': 4127}
    510    >>> dict([(x, x**2) for x in (2, 4, 6)])     # use a list comprehension
     582
     583In addition, dict comprehensions can be used to create dictionaries from
     584arbitrary key and value expressions::
     585
     586   >>> {x: x**2 for x in (2, 4, 6)}
    511587   {2: 4, 4: 16, 6: 36}
    512 
    513 Later in the tutorial, we will learn about Generator Expressions which are even
    514 better suited for the task of supplying key-values pairs to the :func:`dict`
    515 constructor.
    516588
    517589When the keys are simple strings, it is sometimes easier to specify pairs using
     
    526598Looping Techniques
    527599==================
    528 
    529 When looping through dictionaries, the key and corresponding value can be
    530 retrieved at the same time using the :meth:`iteritems` method. ::
    531 
    532    >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
    533    >>> for k, v in knights.iteritems():
    534    ...     print k, v
    535    ...
    536    gallahad the pure
    537    robin the brave
    538600
    539601When looping through a sequence, the position index and corresponding value can
     
    582644   orange
    583645   pear
     646
     647When looping through dictionaries, the key and corresponding value can be
     648retrieved at the same time using the :meth:`iteritems` method. ::
     649
     650   >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
     651   >>> for k, v in knights.iteritems():
     652   ...     print k, v
     653   ...
     654   gallahad the pure
     655   robin the brave
     656
     657To change a sequence you are iterating over while inside the loop (for
     658example to duplicate certain items), it is recommended that you first make
     659a copy.  Looping over a sequence does not implicitly make a copy.  The slice
     660notation makes this especially convenient::
     661
     662   >>> words = ['cat', 'window', 'defenestrate']
     663   >>> for w in words[:]:  # Loop over a slice copy of the entire list.
     664   ...     if len(w) > 6:
     665   ...         words.insert(0, w)
     666   ...
     667   >>> words
     668   ['defenestrate', 'cat', 'window', 'defenestrate']
    584669
    585670
  • python/trunk/Doc/tutorial/errors.rst

    r2 r391  
    121121   ...     pass
    122122
     123Note that the parentheses around this tuple are required, because
     124``except ValueError, e:`` was the syntax used for what is normally
     125written as ``except ValueError as e:`` in modern Python (described
     126below). The old syntax is still supported for backwards compatibility.
     127This means ``except RuntimeError, TypeError`` is not equivalent to
     128``except (RuntimeError, TypeError):`` but to ``except RuntimeError as
     129TypeError:`` which is not what you want.
     130
    123131The last except clause may omit the exception name(s), to serve as a wildcard.
    124132Use this with extreme caution, since it is easy to mask a real programming error
     
    132140       s = f.readline()
    133141       i = int(s.strip())
    134    except IOError as (errno, strerror):
    135        print "I/O error({0}): {1}".format(errno, strerror)
     142   except IOError as e:
     143       print "I/O error({0}): {1}".format(e.errno, e.strerror)
    136144   except ValueError:
    137145       print "Could not convert data to an integer."
     
    178186   ...    print inst.args      # arguments stored in .args
    179187   ...    print inst           # __str__ allows args to printed directly
    180    ...    x, y = inst          # __getitem__ allows args to be unpacked directly
     188   ...    x, y = inst.args
    181189   ...    print 'x =', x
    182190   ...    print 'y =', y
     
    219227   NameError: HiThere
    220228
    221 The argument to :keyword:`raise` is an exception class or instance to be
    222 raised.  There is a deprecated alternate syntax that separates class and
    223 constructor arguments; the above could be written as ``raise NameError,
    224 'HiThere'``.  Since it once was the only one available, the latter form is
    225 prevalent in older code.
     229The sole argument to :keyword:`raise` indicates the exception to be raised.
     230This must be either an exception instance or an exception class (a class that
     231derives from :class:`Exception`).
    226232
    227233If you need to determine whether an exception was raised but don't intend to
     
    392398
    393399   for line in open("myfile.txt"):
    394        print line
     400       print line,
    395401
    396402The problem with this code is that it leaves the file open for an indeterminate
     
    402408   with open("myfile.txt") as f:
    403409       for line in f:
    404            print line
     410           print line,
    405411
    406412After the statement is executed, the file *f* is always closed, even if a
  • python/trunk/Doc/tutorial/floatingpoint.rst

    r2 r391  
    4949   0.0001100110011001100110011001100110011001100110011...
    5050
    51 Stop at any finite number of bits, and you get an approximation.  This is why
    52 you see things like::
    53 
    54    >>> 0.1
    55    0.10000000000000001
    56 
    57 On most machines today, that is what you'll see if you enter 0.1 at a Python
    58 prompt.  You may not, though, because the number of bits used by the hardware to
    59 store floating-point values can vary across machines, and Python only prints a
    60 decimal approximation to the true decimal value of the binary approximation
    61 stored by the machine.  On most machines, if Python were to print the true
    62 decimal value of the binary approximation stored for 0.1, it would have to
    63 display ::
     51Stop at any finite number of bits, and you get an approximation.
     52
     53On a typical machine running Python, there are 53 bits of precision available
     54for a Python float, so the value stored internally when you enter the decimal
     55number ``0.1`` is the binary fraction ::
     56
     57   0.00011001100110011001100110011001100110011001100110011010
     58
     59which is close to, but not exactly equal to, 1/10.
     60
     61It's easy to forget that the stored value is an approximation to the original
     62decimal fraction, because of the way that floats are displayed at the
     63interpreter prompt.  Python only prints a decimal approximation to the true
     64decimal value of the binary approximation stored by the machine.  If Python
     65were to print the true decimal value of the binary approximation stored for
     660.1, it would have to display ::
    6467
    6568   >>> 0.1
    6669   0.1000000000000000055511151231257827021181583404541015625
    6770
    68 instead!  The Python prompt uses the built-in :func:`repr` function to obtain a
    69 string version of everything it displays.  For floats, ``repr(float)`` rounds
    70 the true decimal value to 17 significant digits, giving ::
    71 
    72    0.10000000000000001
    73 
    74 ``repr(float)`` produces 17 significant digits because it turns out that's
    75 enough (on most machines) so that ``eval(repr(x)) == x`` exactly for all finite
    76 floats *x*, but rounding to 16 digits is not enough to make that true.
    77 
    78 Note that this is in the very nature of binary floating-point: this is not a bug
    79 in Python, and it is not a bug in your code either.  You'll see the same kind of
    80 thing in all languages that support your hardware's floating-point arithmetic
    81 (although some languages may not *display* the difference by default, or in all
    82 output modes).
    83 
    84 Python's built-in :func:`str` function produces only 12 significant digits, and
    85 you may wish to use that instead.  It's unusual for ``eval(str(x))`` to
    86 reproduce *x*, but the output may be more pleasant to look at::
    87 
    88    >>> print str(0.1)
     71That is more digits than most people find useful, so Python keeps the number
     72of digits manageable by displaying a rounded value instead ::
     73
     74   >>> 0.1
    8975   0.1
    9076
    9177It's important to realize that this is, in a real sense, an illusion: the value
    9278in the machine is not exactly 1/10, you're simply rounding the *display* of the
    93 true machine value.
    94 
    95 Other surprises follow from this one.  For example, after seeing ::
    96 
    97    >>> 0.1
    98    0.10000000000000001
    99 
    100 you may be tempted to use the :func:`round` function to chop it back to the
    101 single digit you expect.  But that makes no difference::
    102 
    103    >>> round(0.1, 1)
    104    0.10000000000000001
    105 
    106 The problem is that the binary floating-point value stored for "0.1" was already
    107 the best possible binary approximation to 1/10, so trying to round it again
    108 can't make it better:  it was already as good as it gets.
    109 
    110 Another consequence is that since 0.1 is not exactly 1/10, summing ten values of
    111 0.1 may not yield exactly 1.0, either::
     79true machine value.  This fact becomes apparent as soon as you try to do
     80arithmetic with these values ::
     81
     82   >>> 0.1 + 0.2
     83   0.30000000000000004
     84
     85Note that this is in the very nature of binary floating-point: this is not a
     86bug in Python, and it is not a bug in your code either.  You'll see the same
     87kind of thing in all languages that support your hardware's floating-point
     88arithmetic (although some languages may not *display* the difference by
     89default, or in all output modes).
     90
     91Other surprises follow from this one.  For example, if you try to round the
     92value 2.675 to two decimal places, you get this ::
     93
     94   >>> round(2.675, 2)
     95   2.67
     96
     97The documentation for the built-in :func:`round` function says that it rounds
     98to the nearest value, rounding ties away from zero.  Since the decimal fraction
     992.675 is exactly halfway between 2.67 and 2.68, you might expect the result
     100here to be (a binary approximation to) 2.68.  It's not, because when the
     101decimal string ``2.675`` is converted to a binary floating-point number, it's
     102again replaced with a binary approximation, whose exact value is ::
     103
     104   2.67499999999999982236431605997495353221893310546875
     105
     106Since this approximation is slightly closer to 2.67 than to 2.68, it's rounded
     107down.
     108
     109If you're in a situation where you care which way your decimal halfway-cases
     110are rounded, you should consider using the :mod:`decimal` module.
     111Incidentally, the :mod:`decimal` module also provides a nice way to "see" the
     112exact value that's stored in any particular Python float ::
     113
     114   >>> from decimal import Decimal
     115   >>> Decimal(2.675)
     116   Decimal('2.67499999999999982236431605997495353221893310546875')
     117
     118Another consequence is that since 0.1 is not exactly 1/10, summing ten values
     119of 0.1 may not yield exactly 1.0, either::
    112120
    113121   >>> sum = 0.0
     
    116124   ...
    117125   >>> sum
    118    0.99999999999999989
     126   0.9999999999999999
    119127
    120128Binary floating-point arithmetic holds many surprises like this.  The problem
     
    132140While pathological cases do exist, for most casual use of floating-point
    133141arithmetic you'll see the result you expect in the end if you simply round the
    134 display of your final results to the number of decimal digits you expect.
    135 :func:`str` usually suffices, and for finer control see the :meth:`str.format`
    136 method's format specifiers in :ref:`formatstrings`.
     142display of your final results to the number of decimal digits you expect.  For
     143fine control over how a float is displayed see the :meth:`str.format` method's
     144format specifiers in :ref:`formatstrings`.
    137145
    138146
     
    142150====================
    143151
    144 This section explains the "0.1" example in detail, and shows how you can perform
    145 an exact analysis of cases like this yourself.  Basic familiarity with binary
    146 floating-point representation is assumed.
     152This section explains the "0.1" example in detail, and shows how you can
     153perform an exact analysis of cases like this yourself.  Basic familiarity with
     154binary floating-point representation is assumed.
    147155
    148156:dfn:`Representation error` refers to the fact that some (most, actually)
     
    151159others) often won't display the exact decimal number you expect::
    152160
    153    >>> 0.1
    154    0.10000000000000001
    155 
    156 Why is that?  1/10 is not exactly representable as a binary fraction. Almost all
    157 machines today (November 2000) use IEEE-754 floating point arithmetic, and
    158 almost all platforms map Python floats to IEEE-754 "double precision".  754
    159 doubles contain 53 bits of precision, so on input the computer strives to
    160 convert 0.1 to the closest fraction it can of the form *J*/2**\ *N* where *J* is
    161 an integer containing exactly 53 bits.  Rewriting ::
     161   >>> 0.1 + 0.2
     162   0.30000000000000004
     163
     164Why is that?  1/10 and 2/10 are not exactly representable as a binary
     165fraction. Almost all machines today (July 2010) use IEEE-754 floating point
     166arithmetic, and almost all platforms map Python floats to IEEE-754 "double
     167precision".  754 doubles contain 53 bits of precision, so on input the computer
     168strives to convert 0.1 to the closest fraction it can of the form *J*/2**\ *N*
     169where *J* is an integer containing exactly 53 bits.  Rewriting ::
    162170
    163171   1 / 10 ~= J / (2**N)
     
    171179
    172180   >>> 2**52
    173    4503599627370496L
     181   4503599627370496
    174182   >>> 2**53
    175    9007199254740992L
     183   9007199254740992
    176184   >>> 2**56/10
    177    7205759403792793L
    178 
    179 That is, 56 is the only value for *N* that leaves *J* with exactly 53 bits.  The
    180 best possible value for *J* is then that quotient rounded::
     185   7205759403792793
     186
     187That is, 56 is the only value for *N* that leaves *J* with exactly 53 bits.
     188The best possible value for *J* is then that quotient rounded::
    181189
    182190   >>> q, r = divmod(2**56, 10)
    183191   >>> r
    184    6L
     192   6
    185193
    186194Since the remainder is more than half of 10, the best approximation is obtained
     
    188196
    189197   >>> q+1
    190    7205759403792794L
     198   7205759403792794
    191199
    192200Therefore the best possible approximation to 1/10 in 754 double precision is
     
    196204
    197205Note that since we rounded up, this is actually a little bit larger than 1/10;
    198 if we had not rounded up, the quotient would have been a little bit smaller than
    199 1/10.  But in no case can it be *exactly* 1/10!
     206if we had not rounded up, the quotient would have been a little bit smaller
     207than 1/10.  But in no case can it be *exactly* 1/10!
    200208
    201209So the computer never "sees" 1/10:  what it sees is the exact fraction given
     
    208216its 30 most significant decimal digits::
    209217
    210    >>> 7205759403792794 * 10**30 / 2**56
     218   >>> 7205759403792794 * 10**30 // 2**56
    211219   100000000000000005551115123125L
    212220
    213221meaning that the exact number stored in the computer is approximately equal to
    214 the decimal value 0.100000000000000005551115123125.  Rounding that to 17
    215 significant digits gives the 0.10000000000000001 that Python displays (well,
    216 will display on any 754-conforming platform that does best-possible input and
    217 output conversions in its C library --- yours may not!).
    218 
    219 
     222the decimal value 0.100000000000000005551115123125.  In versions prior to
     223Python 2.7 and Python 3.1, Python rounded this value to 17 significant digits,
     224giving '0.10000000000000001'.  In current versions, Python displays a value
     225based on the shortest decimal fraction that rounds correctly back to the true
     226binary value, resulting simply in '0.1'.
  • python/trunk/Doc/tutorial/index.rst

    r2 r391  
    44  The Python Tutorial
    55######################
    6 
    7 :Release: |version|
    8 :Date: |today|
    96
    107Python is an easy to learn, powerful programming language. It has efficient
  • python/trunk/Doc/tutorial/inputoutput.rst

    r2 r391  
    2020See the Library Reference for more information on this.)
    2121
    22 .. index:: module: string
    23 
    2422Often you'll want more control over the formatting of your output than simply
    2523printing space-separated values.  There are two ways to format your output; the
    2624first way is to do all the string handling yourself; using string slicing and
    2725concatenation operations you can create any layout you can imagine.  The
    28 standard module :mod:`string` contains some useful operations for padding
     26string types have some methods that perform useful operations for padding
    2927strings to a given column width; these will be discussed shortly.  The second
    3028way is to use the :meth:`str.format` method.
     29
     30The :mod:`string` module contains a :class:`~string.Template` class which offers
     31yet another way to substitute values into strings.
    3132
    3233One question remains, of course: how do you convert values to strings? Luckily,
     
    3738fairly human-readable, while :func:`repr` is meant to generate representations
    3839which can be read by the interpreter (or will force a :exc:`SyntaxError` if
    39 there is not equivalent syntax).  For objects which don't have a particular
     40there is no equivalent syntax).  For objects which don't have a particular
    4041representation for human consumption, :func:`str` will return the same value as
    4142:func:`repr`.  Many values, such as numbers or structures like lists and
     
    5051   >>> repr(s)
    5152   "'Hello, world.'"
    52    >>> str(0.1)
    53    '0.1'
    54    >>> repr(0.1)
    55    '0.10000000000000001'
     53   >>> str(1.0/7.0)
     54   '0.142857142857'
     55   >>> repr(1.0/7.0)
     56   '0.14285714285714285'
    5657   >>> x = 10 * 3.25
    5758   >>> y = 200 * 200
     
    103104way :keyword:`print` works: it always adds spaces between its arguments.)
    104105
    105 This example demonstrates the :meth:`rjust` method of string objects, which
    106 right-justifies a string in a field of a given width by padding it with spaces
    107 on the left.  There are similar methods :meth:`ljust` and :meth:`center`.  These
    108 methods do not write anything, they just return a new string.  If the input
    109 string is too long, they don't truncate it, but return it unchanged; this will
    110 mess up your column lay-out but that's usually better than the alternative,
    111 which would be lying about a value.  (If you really want truncation you can
    112 always add a slice operation, as in ``x.ljust(n)[:n]``.)
    113 
    114 There is another method, :meth:`zfill`, which pads a numeric string on the left
    115 with zeros.  It understands about plus and minus signs::
     106This example demonstrates the :meth:`str.rjust` method of string
     107objects, which right-justifies a string in a field of a given width by padding
     108it with spaces on the left.  There are similar methods :meth:`str.ljust` and
     109:meth:`str.center`.  These methods do not write anything, they just return a
     110new string.  If the input string is too long, they don't truncate it, but
     111return it unchanged; this will mess up your column lay-out but that's usually
     112better than the alternative, which would be lying about a value.  (If you
     113really want truncation you can always add a slice operation, as in
     114``x.ljust(n)[:n]``.)
     115
     116There is another method, :meth:`str.zfill`, which pads a numeric string on the
     117left with zeros.  It understands about plus and minus signs::
    116118
    117119   >>> '12'.zfill(5)
     
    124126Basic usage of the :meth:`str.format` method looks like this::
    125127
    126    >>> print 'We are the {0} who say "{1}!"'.format('knights', 'Ni')
     128   >>> print 'We are the {} who say "{}!"'.format('knights', 'Ni')
    127129   We are the knights who say "Ni!"
    128130
    129131The brackets and characters within them (called format fields) are replaced with
    130 the objects passed into the :meth:`~str.format` method.  A number in the
     132the objects passed into the :meth:`str.format` method.  A number in the
    131133brackets refers to the position of the object passed into the
    132 :meth:`~str.format` method. ::
     134:meth:`str.format` method. ::
    133135
    134136   >>> print '{0} and {1}'.format('spam', 'eggs')
     
    137139   eggs and spam
    138140
    139 If keyword arguments are used in the :meth:`~str.format` method, their values
     141If keyword arguments are used in the :meth:`str.format` method, their values
    140142are referred to by using the name of the argument. ::
    141143
     
    154156
    155157   >>> import math
    156    >>> print 'The value of PI is approximately {0}.'.format(math.pi)
     158   >>> print 'The value of PI is approximately {}.'.format(math.pi)
    157159   The value of PI is approximately 3.14159265359.
    158    >>> print 'The value of PI is approximately {0!r}.'.format(math.pi)
     160   >>> print 'The value of PI is approximately {!r}.'.format(math.pi)
    159161   The value of PI is approximately 3.141592653589793.
    160162
    161163An optional ``':'`` and format specifier can follow the field name. This allows
    162164greater control over how the value is formatted.  The following example
    163 truncates Pi to three places after the decimal.
     165rounds Pi to three places after the decimal.
    164166
    165167   >>> import math
     
    195197   Jack: 4098; Sjoerd: 4127; Dcab: 8637678
    196198
    197 This is particularly useful in combination with the new built-in :func:`vars`
    198 function, which returns a dictionary containing all local variables.
     199This is particularly useful in combination with the built-in function
     200:func:`vars`, which returns a dictionary containing all local variables.
    199201
    200202For a complete overview of string formatting with :meth:`str.format`, see
     
    206208
    207209The ``%`` operator can also be used for string formatting. It interprets the
    208 left argument much like a :cfunc:`sprintf`\ -style format string to be applied
     210left argument much like a :c:func:`sprintf`\ -style format string to be applied
    209211to the right argument, and returns the string resulting from this formatting
    210212operation. For example::
     
    214216   The value of PI is approximately 3.142.
    215217
    216 Since :meth:`str.format` is quite new, a lot of Python code still uses the ``%``
    217 operator. However, because this old style of formatting will eventually be
    218 removed from the language, :meth:`str.format` should generally be used.
    219 
    220218More information can be found in the :ref:`string-formatting` section.
    221219
     
    235233::
    236234
    237    >>> f = open('/tmp/workfile', 'w')
     235   >>> f = open('workfile', 'w')
    238236   >>> print f
    239    <open file '/tmp/workfile', mode 'w' at 80a0960>
     237   <open file 'workfile', mode 'w' at 80a0960>
    240238
    241239The first argument is a string containing the filename.  The second argument is
     
    294292   ''
    295293
    296 ``f.readlines()`` returns a list containing all the lines of data in the file.
    297 If given an optional parameter *sizehint*, it reads that many bytes from the
    298 file and enough more to complete a line, and returns the lines from that.  This
    299 is often used to allow efficient reading of a large file by lines, but without
    300 having to load the entire file in memory.  Only complete lines will be returned.
    301 ::
    302 
    303    >>> f.readlines()
    304    ['This is the first line of the file.\n', 'Second line of the file\n']
    305 
    306 An alternative approach to reading lines is to loop over the file object. This is
    307 memory efficient, fast, and leads to simpler code::
     294For reading lines from a file, you can loop over the file object. This is memory
     295efficient, fast, and leads to simple code::
    308296
    309297   >>> for line in f:
     
    313301   Second line of the file
    314302
    315 The alternative approach is simpler but does not provide as fine-grained
    316 control.  Since the two approaches manage line buffering differently, they
    317 should not be mixed.
     303If you want to read all the lines of a file in a list you can also use
     304``list(f)`` or ``f.readlines()``.
    318305
    319306``f.write(string)`` writes the contents of *string* to the file, returning
     
    338325beginning of the file as the reference point. ::
    339326
    340    >>> f = open('/tmp/workfile', 'r+')
     327   >>> f = open('workfile', 'r+')
    341328   >>> f.write('0123456789abcdef')
    342329   >>> f.seek(5)     # Go to the 6th byte in the file
     
    362349shorter than writing equivalent :keyword:`try`\ -\ :keyword:`finally` blocks::
    363350
    364     >>> with open('/tmp/workfile', 'r') as f:
     351    >>> with open('workfile', 'r') as f:
    365352    ...     read_data = f.read()
    366353    >>> f.closed
  • python/trunk/Doc/tutorial/interactive.rst

    r2 r391  
    124124   #
    125125   # Store the file in ~/.pystartup, and set an environment variable to point
    126    # to it:  "export PYTHONSTARTUP=/home/user/.pystartup" in bash.
    127    #
    128    # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
    129    # full path to your home directory.
     126   # to it:  "export PYTHONSTARTUP=~/.pystartup" in bash.
    130127
    131128   import atexit
     
    160157
    161158One alternative enhanced interactive interpreter that has been around for quite
    162 some time is `IPython`_, which features tab completion, object exploration and
     159some time is IPython_, which features tab completion, object exploration and
    163160advanced history management.  It can also be thoroughly customized and embedded
    164161into other applications.  Another similar enhanced interactive environment is
    165 `bpython`_.
     162bpython_.
    166163
    167164
     
    170167.. [#] Python will execute the contents of a file identified by the
    171168   :envvar:`PYTHONSTARTUP` environment variable when you start an interactive
    172    interpreter.
     169   interpreter.  To customize Python even for non-interactive mode, see
     170   :ref:`tut-customize`.
    173171
    174172
  • python/trunk/Doc/tutorial/interpreter.rst

    r2 r391  
    2323
    2424On Windows machines, the Python installation is usually placed in
    25 :file:`C:\\Python26`, though you can change this when you're running the
     25:file:`C:\\Python27`, though you can change this when you're running the
    2626installer.  To add this directory to your path,  you can type the following
    2727command into the command prompt in a DOS box::
    2828
    29    set path=%path%;C:\python26
     29   set path=%path%;C:\python27
    3030
    3131Typing an end-of-file character (:kbd:`Control-D` on Unix, :kbd:`Control-Z` on
     
    5959if you had spelled out its full name on the command line.
    6060
    61 Note that there is a difference between ``python file`` and ``python <file``.
    62 In the latter case, input requests from the program, such as calls to
    63 :func:`input` and :func:`raw_input`, are satisfied from *file*.  Since this file
    64 has already been read until the end by the parser before the program starts
    65 executing, the program will encounter end-of-file immediately.  In the former
    66 case (which is usually what you want) they are satisfied from whatever file or
    67 device is connected to standard input of the Python interpreter.
    68 
    6961When a script file is used, it is sometimes useful to be able to run the script
    7062and enter interactive mode afterwards.  This can be done by passing :option:`-i`
    71 before the script.  (This does not work if the script is read from standard
    72 input, for the same reason as explained in the previous paragraph.)
     63before the script.
    7364
    7465
     
    7970
    8071When known to the interpreter, the script name and additional arguments
    81 thereafter are passed to the script in the variable ``sys.argv``, which is a
    82 list of strings.  Its length is at least one; when no script and no arguments
     72thereafter are turned into a list of strings and assigned to the ``argv``
     73variable in the ``sys`` module.  You can access this list by executing ``import
     74sys``.  The length of the list is at least one; when no script and no arguments
    8375are given, ``sys.argv[0]`` is an empty string.  When the script name is given as
    8476``'-'`` (meaning  standard input), ``sys.argv[0]`` is set to ``'-'``.  When
     
    10395
    10496   python
    105    Python 2.6 (#1, Feb 28 2007, 00:02:06)
     97   Python 2.7 (#1, Feb 28 2010, 00:02:06)
    10698   Type "help", "copyright", "credits" or "license" for more information.
    10799   >>>
     
    174166
    175167
     168.. _tut-source-encoding:
     169
    176170Source Code Encoding
    177171--------------------
     
    192186For example, to write Unicode literals including the Euro currency symbol, the
    193187ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value
    194 164.  This script will print the value 8364 (the Unicode codepoint corresponding
    195 to the Euro symbol) and then exit::
     188164.  This script, when saved in the ISO-8859-15 encoding, will print the value
     1898364 (the Unicode codepoint corresponding to the Euro symbol) and then exit::
    196190
    197191   # -*- coding: iso-8859-15 -*-
     
    248242
    249243
     244.. _tut-customize:
     245
     246The Customization Modules
     247-------------------------
     248
     249Python provides two hooks to let you customize it: :mod:`sitecustomize` and
     250:mod:`usercustomize`.  To see how it works, you need first to find the location
     251of your user site-packages directory.  Start Python and run this code:
     252
     253   >>> import site
     254   >>> site.getusersitepackages()
     255   '/home/user/.local/lib/python2.7/site-packages'
     256
     257Now you can create a file named :file:`usercustomize.py` in that directory and
     258put anything you want in it.  It will affect every invocation of Python, unless
     259it is started with the :option:`-s` option to disable the automatic import.
     260
     261:mod:`sitecustomize` works in the same way, but is typically created by an
     262administrator of the computer in the global site-packages directory, and is
     263imported before :mod:`usercustomize`.  See the documentation of the :mod:`site`
     264module for more details.
     265
     266
    250267.. rubric:: Footnotes
    251268
    252269.. [#] A problem with the GNU Readline package may prevent this.
    253 
  • python/trunk/Doc/tutorial/introduction.rst

    r2 r391  
    8383error will occur::
    8484
    85    >>> # try to access an undefined variable
    86    ... n
     85   >>> n  # try to access an undefined variable
    8786   Traceback (most recent call last):
    8887     File "<stdin>", line 1, in <module>
     
    179178   '"Isn\'t," she said.'
    180179
     180The interpreter prints the result of string operations in the same way as they
     181are typed for input: inside quotes, and with quotes and other funny characters
     182escaped by backslashes, to show the precise value.  The string is enclosed in
     183double quotes if the string contains a single quote and no double quotes, else
     184it's enclosed in single quotes.  The :keyword:`print` statement produces a more
     185readable output for such input strings.
     186
    181187String literals can span multiple lines in several ways.  Continuation lines can
    182188be used, with a backslash as the last character on the line indicating that the
     
    190196   print hello
    191197
    192 Note that newlines still need to be embedded in the string using ``\n``; the
     198Note that newlines still need to be embedded in the string using ``\n`` -- the
    193199newline following the trailing backslash is discarded.  This example would print
    194200the following:
     
    233239   This is a rather long string containing\n\
    234240   several lines of text much as you would do in C.
    235 
    236 The interpreter prints the result of string operations in the same way as they
    237 are typed for input: inside quotes, and with quotes and other funny characters
    238 escaped by backslashes, to show the precise value.  The string is enclosed in
    239 double quotes if the string contains a single quote and no double quotes, else
    240 it's enclosed in single quotes.  (The :keyword:`print` statement, described
    241 later, can be used to write strings without quotes or escapes.)
    242241
    243242Strings can be concatenated (glued together) with the ``+`` operator, and
     
    523522   >>> 3*a[:3] + ['Boo!']
    524523   ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']
     524
     525All slice operations return a new list containing the requested elements.  This
     526means that the following slice returns a shallow copy of the list *a*::
     527
     528   >>> a[:]
     529   ['spam', 'eggs', 100, 1234]
    525530
    526531Unlike strings, which are *immutable*, it is possible to change individual
     
    625630
    626631* The *body* of the loop is *indented*: indentation is Python's way of grouping
    627   statements.  Python does not (yet!) provide an intelligent input line editing
    628   facility, so you have to type a tab or space(s) for each indented line.  In
    629   practice you will prepare more complicated input for Python with a text editor;
    630   most text editors have an auto-indent facility.  When a compound statement is
    631   entered interactively, it must be followed by a blank line to indicate
    632   completion (since the parser cannot guess when you have typed the last line).
    633   Note that each line within a basic block must be indented by the same amount.
     632  statements.  At the interactive prompt, you have to type a tab or space(s) for
     633  each indented line.  In practice you will prepare more complicated input
     634  for Python with a text editor; all decent text editors have an auto-indent
     635  facility.  When a compound statement is entered interactively, it must be
     636  followed by a blank line to indicate completion (since the parser cannot
     637  guess when you have typed the last line).  Note that each line within a basic
     638  block must be indented by the same amount.
    634639
    635640* The :keyword:`print` statement writes the value of the expression(s) it is
  • python/trunk/Doc/tutorial/modules.rst

    r2 r391  
    7272A module can contain executable statements as well as function definitions.
    7373These statements are intended to initialize the module. They are executed only
    74 the *first* time the module is imported somewhere. [#]_
     74the *first* time the module name is encountered in an import statement. [#]_
     75(They are also run if the file is executed as a script.)
    7576
    7677Each module has its own private symbol table, which is used as the global symbol
     
    156157.. index:: triple: module; search; path
    157158
    158 When a module named :mod:`spam` is imported, the interpreter searches for a file
    159 named :file:`spam.py` in the current directory, and then in the list of
    160 directories specified by the environment variable :envvar:`PYTHONPATH`.  This
    161 has the same syntax as the shell variable :envvar:`PATH`, that is, a list of
    162 directory names.  When :envvar:`PYTHONPATH` is not set, or when the file is not
    163 found there, the search continues in an installation-dependent default path; on
    164 Unix, this is usually :file:`.:/usr/local/lib/python`.
    165 
    166 Actually, modules are searched in the list of directories given by the variable
    167 ``sys.path`` which is initialized from the directory containing the input script
    168 (or the current directory), :envvar:`PYTHONPATH` and the installation- dependent
    169 default.  This allows Python programs that know what they're doing to modify or
    170 replace the module search path.  Note that because the directory containing the
    171 script being run is on the search path, it is important that the script not have
    172 the same name as a standard module, or Python will attempt to load the script as
    173 a module when that module is imported. This will generally be an error.  See
    174 section :ref:`tut-standardmodules` for more information.
     159When a module named :mod:`spam` is imported, the interpreter first searches for
     160a built-in module with that name. If not found, it then searches for a file
     161named :file:`spam.py` in a list of directories given by the variable
     162:data:`sys.path`.  :data:`sys.path` is initialized from these locations:
     163
     164* the directory containing the input script (or the current directory).
     165* :envvar:`PYTHONPATH` (a list of directory names, with the same syntax as the
     166  shell variable :envvar:`PATH`).
     167* the installation-dependent default.
     168
     169After initialization, Python programs can modify :data:`sys.path`.  The
     170directory containing the script being run is placed at the beginning of the
     171search path, ahead of the standard library path. This means that scripts in that
     172directory will be loaded instead of modules of the same name in the library
     173directory. This is an error unless the replacement is intended.  See section
     174:ref:`tut-standardmodules` for more information.
    175175
    176176
     
    244244for efficiency or to provide access to operating system primitives such as
    245245system calls.  The set of such modules is a configuration option which also
    246 depends on the underlying platform For example, the :mod:`winreg` module is only
     246depends on the underlying platform. For example, the :mod:`winreg` module is only
    247247provided on Windows systems. One particular module deserves some attention:
    248248:mod:`sys`, which is built into every Python interpreter.  The variables
     
    284284   >>> dir(fibo)
    285285   ['__name__', 'fib', 'fib2']
    286    >>> dir(sys)
    287    ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
    288     '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
    289     'builtin_module_names', 'byteorder', 'callstats', 'copyright',
    290     'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
    291     'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
    292     'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
    293     'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',
    294     'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
    295     'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
     286   >>> dir(sys)  # doctest: +NORMALIZE_WHITESPACE
     287   ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__',
     288    '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache',
     289    '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv',
     290    'builtin_module_names', 'byteorder', 'call_tracing', 'callstats',
     291    'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info',
     292    'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix',
     293    'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
     294    'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
     295    'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
     296    'getrefcount', 'getsizeof', 'gettotalrefcount', 'gettrace', 'hexversion',
     297    'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules',
     298    'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
     299    'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile',
     300    'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion',
    296301    'version', 'version_info', 'warnoptions']
    297302
     
    302307   >>> fib = fibo.fib
    303308   >>> dir()
    304    ['__builtins__', '__doc__', '__file__', '__name__', 'a', 'fib', 'fibo', 'sys']
     309   ['__builtins__', '__name__', '__package__', 'a', 'fib', 'fibo', 'sys']
    305310
    306311Note that it lists all types of names: variables, modules, functions, etc.
     
    313318
    314319   >>> import __builtin__
    315    >>> dir(__builtin__)
    316    ['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning',
    317     'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
    318     'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError',
     320   >>> dir(__builtin__)  # doctest: +NORMALIZE_WHITESPACE
     321   ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
     322    'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError',
     323    'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError',
     324    'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning',
    319325    'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
    320326    'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
     
    325331    'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
    326332    'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
    327     'UserWarning', 'ValueError', 'Warning', 'WindowsError',
     333    'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning',
    328334    'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
    329     '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer',
    330     'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile',
    331     'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
    332     'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
    333     'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
    334     'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
    335     'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
    336     'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
    337     'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set',
    338     'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
     335    '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring',
     336    'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr',
     337    'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright',
     338    'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval',
     339    'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset',
     340    'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input',
     341    'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license',
     342    'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next',
     343    'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit',
     344    'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round',
     345    'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
    339346    'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
    340347
     
    362369artificial stereo effect), so in addition you will be writing a never-ending
    363370stream of modules to perform these operations.  Here's a possible structure for
    364 your package (expressed in terms of a hierarchical filesystem)::
     371your package (expressed in terms of a hierarchical filesystem):
     372
     373.. code-block:: text
    365374
    366375   sound/                          Top-level package
     
    459468new version of the package is released.  Package authors may also decide not to
    460469support it, if they don't see a use for importing \* from their package.  For
    461 example, the file :file:`sounds/effects/__init__.py` could contain the following
     470example, the file :file:`sound/effects/__init__.py` could contain the following
    462471code::
    463472
     
    545554
    546555.. [#] In fact function definitions are also 'statements' that are 'executed'; the
    547    execution of a module-level function enters the function name in the module's
    548    global symbol table.
    549 
     556   execution of a module-level function definition enters the function name in
     557   the module's global symbol table.
     558
  • python/trunk/Doc/tutorial/stdlib.rst

    r2 r391  
    1515
    1616   >>> import os
    17    >>> os.system('time 0:02')
    18    0
    1917   >>> os.getcwd()      # Return the current working directory
    2018   'C:\\Python26'
    21    >>> os.chdir('/server/accesslogs')
     19   >>> os.chdir('/server/accesslogs')   # Change current working directory
     20   >>> os.system('mkdir today')   # Run the command mkdir in the system shell
     21   0
    2222
    2323Be sure to use the ``import os`` style instead of ``from os import *``.  This
     
    7373The :mod:`getopt` module processes *sys.argv* using the conventions of the Unix
    7474:func:`getopt` function.  More powerful and flexible command line processing is
    75 provided by the :mod:`optparse` module.
     75provided by the :mod:`argparse` module.
    7676
    7777
     
    146146
    147147There are a number of modules for accessing the internet and processing internet
    148 protocols. Two of the simplest are :mod:`urllib2` for retrieving data from urls
     148protocols. Two of the simplest are :mod:`urllib2` for retrieving data from URLs
    149149and :mod:`smtplib` for sending mail::
    150150
     
    279279           self.assertEqual(average([20, 30, 70]), 40.0)
    280280           self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
    281            self.assertRaises(ZeroDivisionError, average, [])
    282            self.assertRaises(TypeError, average, 20, 30, 70)
     281           with self.assertRaises(ZeroDivisionError):
     282               average([])
     283           with self.assertRaises(TypeError):
     284               average(20, 30, 70)
    283285
    284286   unittest.main() # Calling from the command line invokes all tests
  • python/trunk/Doc/tutorial/stdlib2.rst

    r2 r391  
    7272==========
    7373
    74 The :mod:`string` module includes a versatile :class:`Template` class with a
    75 simplified syntax suitable for editing by end-users.  This allows users to
    76 customize their applications without having to alter the application.
     74The :mod:`string` module includes a versatile :class:`~string.Template` class
     75with a simplified syntax suitable for editing by end-users.  This allows users
     76to customize their applications without having to alter the application.
    7777
    7878The format uses placeholder names formed by ``$`` with valid Python identifiers
     
    8686   'Nottinghamfolk send $10 to the ditch fund.'
    8787
    88 The :meth:`substitute` method raises a :exc:`KeyError` when a placeholder is not
    89 supplied in a dictionary or a keyword argument. For mail-merge style
    90 applications, user supplied data may be incomplete and the
    91 :meth:`safe_substitute` method may be more appropriate --- it will leave
    92 placeholders unchanged if data is missing::
     88The :meth:`~string.Template.substitute` method raises a :exc:`KeyError` when a
     89placeholder is not supplied in a dictionary or a keyword argument.  For
     90mail-merge style applications, user supplied data may be incomplete and the
     91:meth:`~string.Template.safe_substitute` method may be more appropriate ---
     92it will leave placeholders unchanged if data is missing::
    9393
    9494   >>> t = Template('Return the $item to $owner.')
     
    9696   >>> t.substitute(d)
    9797   Traceback (most recent call last):
    98      . . .
     98     ...
    9999   KeyError: 'owner'
    100100   >>> t.safe_substitute(d)
     
    133133=======================================
    134134
    135 The :mod:`struct` module provides :func:`pack` and :func:`unpack` functions for
    136 working with variable length binary record formats.  The following example shows
     135The :mod:`struct` module provides :func:`~struct.pack` and
     136:func:`~struct.unpack` functions for working with variable length binary
     137record formats.  The following example shows
    137138how to loop through header information in a ZIP file without using the
    138139:mod:`zipfile` module.  Pack codes ``"H"`` and ``"I"`` represent two and four
     
    219220   logging.critical('Critical error -- shutting down')
    220221
    221 This produces the following output::
     222This produces the following output:
     223
     224.. code-block:: none
    222225
    223226   WARNING:root:Warning:config file server.conf not found
     
    228231is sent to standard error.  Other output options include routing messages
    229232through email, datagrams, sockets, or to an HTTP Server.  New filters can select
    230 different routing based on message priority: :const:`DEBUG`, :const:`INFO`,
    231 :const:`WARNING`, :const:`ERROR`, and :const:`CRITICAL`.
     233different routing based on message priority: :const:`~logging.DEBUG`,
     234:const:`~logging.INFO`, :const:`~logging.WARNING`, :const:`~logging.ERROR`,
     235and :const:`~logging.CRITICAL`.
    232236
    233237The logging system can be configured directly from Python or can be loaded from
     
    256260   >>> class A:
    257261   ...     def __init__(self, value):
    258    ...             self.value = value
     262   ...         self.value = value
    259263   ...     def __repr__(self):
    260    ...             return str(self.value)
     264   ...         return str(self.value)
    261265   ...
    262266   >>> a = A(10)                   # create a reference
     
    286290performance trade-offs.
    287291
    288 The :mod:`array` module provides an :class:`array()` object that is like a list
    289 that stores only homogeneous data and stores it more compactly.  The following
    290 example shows an array of numbers stored as two byte unsigned binary numbers
    291 (typecode ``"H"``) rather than the usual 16 bytes per entry for regular lists of
    292 Python int objects::
     292The :mod:`array` module provides an :class:`~array.array()` object that is like
     293a list that stores only homogeneous data and stores it more compactly.  The
     294following example shows an array of numbers stored as two byte unsigned binary
     295numbers (typecode ``"H"``) rather than the usual 16 bytes per entry for regular
     296lists of Python int objects::
    293297
    294298   >>> from array import array
     
    299303   array('H', [10, 700])
    300304
    301 The :mod:`collections` module provides a :class:`deque()` object that is like a
    302 list with faster appends and pops from the left side but slower lookups in the
    303 middle. These objects are well suited for implementing queues and breadth first
    304 tree searches::
     305The :mod:`collections` module provides a :class:`~collections.deque()` object
     306that is like a list with faster appends and pops from the left side but slower
     307lookups in the middle. These objects are well suited for implementing queues
     308and breadth first tree searches::
    305309
    306310   >>> from collections import deque
     
    309313   >>> print "Handling", d.popleft()
    310314   Handling task1
     315
     316::
    311317
    312318   unsearched = deque([starting_node])
     
    346352=================================
    347353
    348 The :mod:`decimal` module offers a :class:`Decimal` datatype for decimal
    349 floating point arithmetic.  Compared to the built-in :class:`float`
     354The :mod:`decimal` module offers a :class:`~decimal.Decimal` datatype for
     355decimal floating point arithmetic.  Compared to the built-in :class:`float`
    350356implementation of binary floating point, the class is especially helpful for
    351357
     
    363369
    364370   >>> from decimal import *
    365    >>> Decimal('0.70') * Decimal('1.05')
     371   >>> x = Decimal('0.70') * Decimal('1.05')
     372   >>> x
    366373   Decimal('0.7350')
    367    >>> .70 * 1.05
    368    0.73499999999999999
    369 
    370 The :class:`Decimal` result keeps a trailing zero, automatically inferring four
    371 place significance from multiplicands with two place significance.  Decimal
    372 reproduces mathematics as done by hand and avoids issues that can arise when
    373 binary floating point cannot exactly represent decimal quantities.
    374 
    375 Exact representation enables the :class:`Decimal` class to perform modulo
    376 calculations and equality tests that are unsuitable for binary floating point::
     374   >>> x.quantize(Decimal('0.01'))  # round to nearest cent
     375   Decimal('0.74')
     376   >>> round(.70 * 1.05, 2)         # same calculation with floats
     377   0.73
     378
     379The :class:`~decimal.Decimal` result keeps a trailing zero, automatically
     380inferring four place significance from multiplicands with two place
     381significance.  Decimal reproduces mathematics as done by hand and avoids
     382issues that can arise when binary floating point cannot exactly represent
     383decimal quantities.
     384
     385Exact representation enables the :class:`~decimal.Decimal` class to perform
     386modulo calculations and equality tests that are unsuitable for binary floating
     387point::
    377388
    378389   >>> Decimal('1.00') % Decimal('.10')
  • python/trunk/Doc/tutorial/whatnow.rst

    r2 r391  
    5555around 120 postings a day (with peaks up to several hundred), asking (and
    5656answering) questions, suggesting new features, and announcing new modules.
    57 Before posting, be sure to check the list of `Frequently Asked Questions
    58 <http://www.python.org/doc/faq/>`_ (also called the FAQ), or look for it in the
    59 :file:`Misc/` directory of the Python source distribution.  Mailing list
     57Before posting, be sure to check the list of :ref:`Frequently Asked Questions
     58<faq-index>` (also called the FAQ).  Mailing list
    6059archives are available at http://mail.python.org/pipermail/. The FAQ answers
    6160many of the questions that come up again and again, and may already contain the
Note: See TracChangeset for help on using the changeset viewer.