rest25/tutorial/stdlib2.rst => rest262/tutorial/stdlib2.rst
8programming needs.  These modules rarely occur in small scripts.
9
10
11.. _tut-output-formatting:
12
13Output Formatting
14=================
15
n16-The :mod:`repr` (XXX reference: ../lib/module-repr.html) module provides a
n16+The :mod:`repr` module provides a version of :func:`repr` customized for
17-version of :func:`repr` customized for abbreviated displays of large or deeply
17+abbreviated displays of large or deeply nested containers::
18-nested containers::
19
n20-   >>> import repr   
n19+   >>> import repr
21   >>> repr.repr(set('supercalifragilisticexpialidocious'))
22   "set(['a', 'c', 'd', 'e', 'f', 'g', ...])"
23
n24-The :mod:`pprint` (XXX reference: ../lib/module-pprint.html) module offers more
n23+The :mod:`pprint` module offers more sophisticated control over printing both
25-sophisticated control over printing both built-in and user defined objects in a
24+built-in and user defined objects in a way that is readable by the interpreter.
26-way that is readable by the interpreter.  When the result is longer than one
25+When the result is longer than one line, the "pretty printer" adds line breaks
27-line, the "pretty printer" adds line breaks and indentation to more clearly
26+and indentation to more clearly reveal data structure::
28-reveal data structure::
29
30   >>> import pprint
31   >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
32   ...     'yellow'], 'blue']]]
33   ...
34   >>> pprint.pprint(t, width=30)
35   [[[['black', 'cyan'],
36      'white',
37      ['green', 'red']],
38     [['magenta', 'yellow'],
39      'blue']]]
40
n41-The :mod:`textwrap` (XXX reference: ../lib/module-textwrap.html) module formats
n39+The :mod:`textwrap` module formats paragraphs of text to fit a given screen
42-paragraphs of text to fit a given screen width::
40+width::
43
44   >>> import textwrap
45   >>> doc = """The wrap() method is just like fill() except that it returns
46   ... a list of strings instead of one big string with newlines to separate
47   ... the wrapped lines."""
48   ...
49   >>> print textwrap.fill(doc, width=40)
50   The wrap() method is just like fill()
51   except that it returns a list of strings
52   instead of one big string with newlines
53   to separate the wrapped lines.
54
n55-The :mod:`locale` (XXX reference: ../lib/module-locale.html) module accesses a
n53+The :mod:`locale` module accesses a database of culture specific data formats.
56-database of culture specific data formats.  The grouping attribute of locale's
54+The grouping attribute of locale's format function provides a direct way of
57-format function provides a direct way of formatting numbers with group
55+formatting numbers with group separators::
58-separators::
59
60   >>> import locale
61   >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
62   'English_United States.1252'
63   >>> conv = locale.localeconv()          # get a mapping of conventions
64   >>> x = 1234567.8
65   >>> locale.format("%d", x, grouping=True)
66   '1,234,567'
67   >>> locale.format("%s%.*f", (conv['currency_symbol'],
n68-   ...        conv['frac_digits'], x), grouping=True)
n65+   ...               conv['frac_digits'], x), grouping=True)
69   '$1,234,567.80'
70
71
72.. _tut-templating:
73
74Templating
75==========
76
n77-The :mod:`string` (XXX reference: ../lib/module-string.html) module includes a
n74+The :mod:`string` module includes a versatile :class:`Template` class with a
78-versatile :class:`Template` class with a simplified syntax suitable for editing
75+simplified syntax suitable for editing by end-users.  This allows users to
79-by end-users.  This allows users to customize their applications without having
76+customize their applications without having to alter the application.
80-to alter the application.
81
82The format uses placeholder names formed by ``$`` with valid Python identifiers
83(alphanumeric characters and underscores).  Surrounding the placeholder with
84braces allows it to be followed by more alphanumeric letters with no intervening
85spaces.  Writing ``$$`` creates a single escaped ``$``::
86
87   >>> from string import Template
88   >>> t = Template('${village}folk send $$10 to $cause.')
115   >>> fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format):  ')
116   Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f
117
118   >>> t = BatchRename(fmt)
119   >>> date = time.strftime('%d%b%y')
120   >>> for i, filename in enumerate(photofiles):
121   ...     base, ext = os.path.splitext(filename)
122   ...     newname = t.substitute(d=date, n=i, f=ext)
n123-   ...     print '%s --> %s' % (filename, newname)
n119+   ...     print '{0} --> {1}'.format(filename, newname)
124
125   img_1074.jpg --> Ashley_0.jpg
126   img_1076.jpg --> Ashley_1.jpg
127   img_1077.jpg --> Ashley_2.jpg
128
129Another application for templating is separating program logic from the details
130of multiple output formats.  This makes it possible to substitute custom
131templates for XML files, plain text reports, and HTML web reports.
132
133
134.. _tut-binary-formats:
135
136Working with Binary Data Record Layouts
137=======================================
138
n139-The :mod:`struct` (XXX reference: ../lib/module-struct.html) module provides
n135+The :mod:`struct` module provides :func:`pack` and :func:`unpack` functions for
140-:func:`pack` and :func:`unpack` functions for working with variable length
136+working with variable length binary record formats.  The following example shows
141-binary record formats.  The following example shows how to loop through header
137+how to loop through header information in a ZIP file without using the
142-information in a ZIP file (with pack codes ``"H"`` and ``"L"`` representing two
138+:mod:`zipfile` module.  Pack codes ``"H"`` and ``"I"`` represent two and four
143-and four byte unsigned numbers respectively)::
139+byte unsigned numbers respectively.  The ``"<"`` indicates that they are
140+standard size and in little-endian byte order::
144
145   import struct
146
147   data = open('myfile.zip', 'rb').read()
148   start = 0
149   for i in range(3):                      # show the first 3 file headers
150       start += 14
n151-       fields = struct.unpack('LLLHH', data[start:start+16])
n148+       fields = struct.unpack('<IIIHH', data[start:start+16])
152       crc32, comp_size, uncomp_size, filenamesize, extra_size = fields
153
154       start += 16
155       filename = data[start:start+filenamesize]
156       start += filenamesize
157       extra = data[start:start+extra_size]
158       print filename, hex(crc32), comp_size, uncomp_size
159
165Multi-threading
166===============
167
168Threading is a technique for decoupling tasks which are not sequentially
169dependent.  Threads can be used to improve the responsiveness of applications
170that accept user input while other tasks run in the background.  A related use
171case is running I/O in parallel with computations in another thread.
172
n173-The following code shows how the high level :mod:`threading` (XXX reference:
n170+The following code shows how the high level :mod:`threading` module can run
174-../lib/module-threading.html) module can run tasks in background while the main
171+tasks in background while the main program continues to run::
175-program continues to run::
176
177   import threading, zipfile
178
179   class AsyncZip(threading.Thread):
180       def __init__(self, infile, outfile):
n181-           threading.Thread.__init__(self)        
n177+           threading.Thread.__init__(self)
182           self.infile = infile
183           self.outfile = outfile
184       def run(self):
185           f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
186           f.write(self.infile)
187           f.close()
188           print 'Finished background zip of: ', self.infile
189
197The principal challenge of multi-threaded applications is coordinating threads
198that share data or other resources.  To that end, the threading module provides
199a number of synchronization primitives including locks, events, condition
200variables, and semaphores.
201
202While those tools are powerful, minor design errors can result in problems that
203are difficult to reproduce.  So, the preferred approach to task coordination is
204to concentrate all access to a resource in a single thread and then use the
n205-:mod:`Queue` (XXX reference: ../lib/module-Queue.html) module to feed that
n201+:mod:`Queue` module to feed that thread with requests from other threads.
206-thread with requests from other threads.  Applications using :class:`Queue`
202+Applications using :class:`Queue.Queue` objects for inter-thread communication
207-objects for inter-thread communication and coordination are easier to design,
203+and coordination are easier to design, more readable, and more reliable.
208-more readable, and more reliable.
209
210
211.. _tut-logging:
212
213Logging
214=======
215
n216-The :mod:`logging` (XXX reference: ../lib/module-logging.html) module offers a
n211+The :mod:`logging` module offers a full featured and flexible logging system.
217-full featured and flexible logging system.  At its simplest, log messages are
212+At its simplest, log messages are sent to a file or to ``sys.stderr``::
218-sent to a file or to ``sys.stderr``::
219
220   import logging
221   logging.debug('Debugging information')
222   logging.info('Informational message')
223   logging.warning('Warning:config file %s not found', 'server.conf')
224   logging.error('Error occurred')
225   logging.critical('Critical error -- shutting down')
226
242
243
244.. _tut-weak-references:
245
246Weak References
247===============
248
249Python does automatic memory management (reference counting for most objects and
n250-garbage collection to eliminate cycles).  The memory is freed shortly after the
n244+:term:`garbage collection` to eliminate cycles).  The memory is freed shortly
251-last reference to it has been eliminated.
245+after the last reference to it has been eliminated.
252
253This approach works fine for most applications but occasionally there is a need
254to track objects only as long as they are being used by something else.
255Unfortunately, just tracking them creates a reference that makes them permanent.
n256-The :mod:`weakref` (XXX reference: ../lib/module-weakref.html) module provides
n250+The :mod:`weakref` module provides tools for tracking objects without creating a
257-tools for tracking objects without creating a reference.  When the object is no
251+reference.  When the object is no longer needed, it is automatically removed
258-longer needed, it is automatically removed from a weakref table and a callback
252+from a weakref table and a callback is triggered for weakref objects.  Typical
259-is triggered for weakref objects.  Typical applications include caching objects
253+applications include caching objects that are expensive to create::
260-that are expensive to create::
261
262   >>> import weakref, gc
263   >>> class A:
264   ...     def __init__(self, value):
265   ...             self.value = value
266   ...     def __repr__(self):
267   ...             return str(self.value)
268   ...
271   >>> d['primary'] = a            # does not create a reference
272   >>> d['primary']                # fetch the object if it is still alive
273   10
274   >>> del a                       # remove the one reference
275   >>> gc.collect()                # run garbage collection right away
276   0
277   >>> d['primary']                # entry was automatically removed
278   Traceback (most recent call last):
n279-     File "<pyshell#108>", line 1, in -toplevel-
n272+     File "<stdin>", line 1, in <module>
280       d['primary']                # entry was automatically removed
n281-     File "C:/PY24/lib/weakref.py", line 46, in __getitem__
n274+     File "C:/python26/lib/weakref.py", line 46, in __getitem__
282       o = self.data[key]()
283   KeyError: 'primary'
284
285
286.. _tut-list-tools:
287
288Tools for Working with Lists
289============================
290
291Many data structure needs can be met with the built-in list type. However,
292sometimes there is a need for alternative implementations with different
293performance trade-offs.
294
n295-The :mod:`array` (XXX reference: ../lib/module-array.html) module provides an
n288+The :mod:`array` module provides an :class:`array()` object that is like a list
296-:class:`array()` object that is like a list that stores only homogenous data and
289+that stores only homogeneous data and stores it more compactly.  The following
297-stores it more compactly.  The following example shows an array of numbers
290+example shows an array of numbers stored as two byte unsigned binary numbers
298-stored as two byte unsigned binary numbers (typecode ``"H"``) rather than the
291+(typecode ``"H"``) rather than the usual 16 bytes per entry for regular lists of
299-usual 16 bytes per entry for regular lists of python int objects::
292+python int objects::
300
301   >>> from array import array
302   >>> a = array('H', [4000, 10, 700, 22222])
303   >>> sum(a)
304   26932
305   >>> a[1:3]
306   array('H', [10, 700])
307
n308-The :mod:`collections` (XXX reference: ../lib/module-collections.html) module
n301+The :mod:`collections` module provides a :class:`deque()` object that is like a
309-provides a :class:`deque()` object that is like a list with faster appends and
302+list with faster appends and pops from the left side but slower lookups in the
310-pops from the left side but slower lookups in the middle. These objects are well
303+middle. These objects are well suited for implementing queues and breadth first
311-suited for implementing queues and breadth first tree searches::
304+tree searches::
312
313   >>> from collections import deque
314   >>> d = deque(["task1", "task2", "task3"])
315   >>> d.append("task4")
316   >>> print "Handling", d.popleft()
317   Handling task1
318
319   unsearched = deque([starting_node])
320   def breadth_first_search(unsearched):
321       node = unsearched.popleft()
322       for m in gen_moves(node):
323           if is_goal(m):
324               return m
325           unsearched.append(m)
326
327In addition to alternative list implementations, the library also offers other
n328-tools such as the :mod:`bisect` (XXX reference: ../lib/module-bisect.html)
n321+tools such as the :mod:`bisect` module with functions for manipulating sorted
329-module with functions for manipulating sorted lists::
322+lists::
330
331   >>> import bisect
332   >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
333   >>> bisect.insort(scores, (300, 'ruby'))
334   >>> scores
335   [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
336
n337-The :mod:`heapq` (XXX reference: ../lib/module-heapq.html) module provides
n330+The :mod:`heapq` module provides functions for implementing heaps based on
338-functions for implementing heaps based on regular lists.  The lowest valued
331+regular lists.  The lowest valued entry is always kept at position zero.  This
339-entry is always kept at position zero.  This is useful for applications which
332+is useful for applications which repeatedly access the smallest element but do
340-repeatedly access the smallest element but do not want to run a full list sort::
333+not want to run a full list sort::
341
342   >>> from heapq import heapify, heappop, heappush
343   >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
344   >>> heapify(data)                      # rearrange the list into heap order
345   >>> heappush(data, -5)                 # add a new entry
346   >>> [heappop(data) for i in range(3)]  # fetch the three smallest entries
347   [-5, 0, 1]
348
349
350.. _tut-decimal-fp:
351
352Decimal Floating Point Arithmetic
353=================================
354
n355-The :mod:`decimal` (XXX reference: ../lib/module-decimal.html) module offers a
n348+The :mod:`decimal` module offers a :class:`Decimal` datatype for decimal
356-:class:`Decimal` datatype for decimal floating point arithmetic.  Compared to
349+floating point arithmetic.  Compared to the built-in :class:`float`
357-the built-in :class:`float` implementation of binary floating point, the new
350+implementation of binary floating point, the new class is especially helpful for
358-class is especially helpful for financial applications and other uses which
351+financial applications and other uses which require exact decimal
359-require exact decimal representation, control over precision, control over
352+representation, control over precision, control over rounding to meet legal or
360-rounding to meet legal or regulatory requirements, tracking of significant
353+regulatory requirements, tracking of significant decimal places, or for
361-decimal places, or for applications where the user expects the results to match
354+applications where the user expects the results to match calculations done by
362-calculations done by hand.
355+hand.
363
364For example, calculating a 5% tax on a 70 cent phone charge gives different
365results in decimal floating point and binary floating point. The difference
366becomes significant if the results are rounded to the nearest cent::
367
n368-   >>> from decimal import *       
n361+   >>> from decimal import *
369   >>> Decimal('0.70') * Decimal('1.05')
370   Decimal("0.7350")
371   >>> .70 * 1.05
n372-   0.73499999999999999       
n365+   0.73499999999999999
373
374The :class:`Decimal` result keeps a trailing zero, automatically inferring four
375place significance from multiplicands with two place significance.  Decimal
376reproduces mathematics as done by hand and avoids issues that can arise when
377binary floating point cannot exactly represent decimal quantities.
378
379Exact representation enables the :class:`Decimal` class to perform modulo
380calculations and equality tests that are unsuitable for binary floating point::
382   >>> Decimal('1.00') % Decimal('.10')
383   Decimal("0.00")
384   >>> 1.00 % 0.10
385   0.09999999999999995
386
387   >>> sum([Decimal('0.1')]*10) == Decimal('1.0')
388   True
389   >>> sum([0.1]*10) == 1.0
t390-   False      
t383+   False
391
392The :mod:`decimal` module provides arithmetic with as much precision as needed::
393
394   >>> getcontext().prec = 36
395   >>> Decimal(1) / Decimal(7)
396   Decimal("0.142857142857142857142857142857142857")
397
398
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op