blob: 4e8d37e52181670a711e566e2edbdc2f663b6bc2 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _tut-brieftourtwo:
2
3*********************************************
4Brief Tour of the Standard Library -- Part II
5*********************************************
6
7This second tour covers more advanced modules that support professional
8programming needs. These modules rarely occur in small scripts.
9
10
11.. _tut-output-formatting:
12
13Output Formatting
14=================
15
16The :mod:`repr` module provides a version of :func:`repr` customized for
17abbreviated displays of large or deeply nested containers::
18
19 >>> import repr
20 >>> repr.repr(set('supercalifragilisticexpialidocious'))
21 "set(['a', 'c', 'd', 'e', 'f', 'g', ...])"
22
23The :mod:`pprint` module offers more sophisticated control over printing both
24built-in and user defined objects in a way that is readable by the interpreter.
25When the result is longer than one line, the "pretty printer" adds line breaks
26and indentation to more clearly reveal data structure::
27
28 >>> import pprint
29 >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
30 ... 'yellow'], 'blue']]]
31 ...
32 >>> pprint.pprint(t, width=30)
33 [[[['black', 'cyan'],
34 'white',
35 ['green', 'red']],
36 [['magenta', 'yellow'],
37 'blue']]]
38
39The :mod:`textwrap` module formats paragraphs of text to fit a given screen
40width::
41
42 >>> import textwrap
43 >>> doc = """The wrap() method is just like fill() except that it returns
44 ... a list of strings instead of one big string with newlines to separate
45 ... the wrapped lines."""
46 ...
Georg Brandl6911e3c2007-09-04 07:15:32 +000047 >>> print(textwrap.fill(doc, width=40))
Georg Brandl116aa622007-08-15 14:28:22 +000048 The wrap() method is just like fill()
49 except that it returns a list of strings
50 instead of one big string with newlines
51 to separate the wrapped lines.
52
53The :mod:`locale` module accesses a database of culture specific data formats.
54The grouping attribute of locale's format function provides a direct way of
55formatting numbers with group separators::
56
57 >>> import locale
58 >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
59 'English_United States.1252'
60 >>> conv = locale.localeconv() # get a mapping of conventions
61 >>> x = 1234567.8
62 >>> locale.format("%d", x, grouping=True)
63 '1,234,567'
64 >>> locale.format("%s%.*f", (conv['currency_symbol'],
65 ... conv['frac_digits'], x), grouping=True)
66 '$1,234,567.80'
67
68
69.. _tut-templating:
70
71Templating
72==========
73
74The :mod:`string` module includes a versatile :class:`Template` class with a
75simplified syntax suitable for editing by end-users. This allows users to
76customize their applications without having to alter the application.
77
78The format uses placeholder names formed by ``$`` with valid Python identifiers
79(alphanumeric characters and underscores). Surrounding the placeholder with
80braces allows it to be followed by more alphanumeric letters with no intervening
81spaces. Writing ``$$`` creates a single escaped ``$``::
82
83 >>> from string import Template
84 >>> t = Template('${village}folk send $$10 to $cause.')
85 >>> t.substitute(village='Nottingham', cause='the ditch fund')
86 'Nottinghamfolk send $10 to the ditch fund.'
87
88The :meth:`substitute` method raises a :exc:`KeyError` when a placeholder is not
89supplied in a dictionary or a keyword argument. For mail-merge style
90applications, user supplied data may be incomplete and the
91:meth:`safe_substitute` method may be more appropriate --- it will leave
92placeholders unchanged if data is missing::
93
94 >>> t = Template('Return the $item to $owner.')
95 >>> d = dict(item='unladen swallow')
96 >>> t.substitute(d)
97 Traceback (most recent call last):
98 . . .
99 KeyError: 'owner'
100 >>> t.safe_substitute(d)
101 'Return the unladen swallow to $owner.'
102
103Template subclasses can specify a custom delimiter. For example, a batch
104renaming utility for a photo browser may elect to use percent signs for
105placeholders such as the current date, image sequence number, or file format::
106
Georg Brandl8d5c3922007-12-02 22:48:17 +0000107 >>> import time, os.path
Georg Brandl116aa622007-08-15 14:28:22 +0000108 >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
109 >>> class BatchRename(Template):
110 ... delimiter = '%'
Georg Brandl8d5c3922007-12-02 22:48:17 +0000111 >>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ')
Georg Brandl116aa622007-08-15 14:28:22 +0000112 Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f
113
114 >>> t = BatchRename(fmt)
115 >>> date = time.strftime('%d%b%y')
116 >>> for i, filename in enumerate(photofiles):
117 ... base, ext = os.path.splitext(filename)
118 ... newname = t.substitute(d=date, n=i, f=ext)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000119 ... print('%s --> %s' % (filename, newname))
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121 img_1074.jpg --> Ashley_0.jpg
122 img_1076.jpg --> Ashley_1.jpg
123 img_1077.jpg --> Ashley_2.jpg
124
125Another application for templating is separating program logic from the details
126of multiple output formats. This makes it possible to substitute custom
127templates for XML files, plain text reports, and HTML web reports.
128
129
130.. _tut-binary-formats:
131
132Working with Binary Data Record Layouts
133=======================================
134
135The :mod:`struct` module provides :func:`pack` and :func:`unpack` functions for
136working with variable length binary record formats. The following example shows
137how to loop through header information in a ZIP file (with pack codes ``"H"``
138and ``"L"`` representing two and four byte unsigned numbers respectively)::
139
140 import struct
141
142 data = open('myfile.zip', 'rb').read()
143 start = 0
144 for i in range(3): # show the first 3 file headers
145 start += 14
146 fields = struct.unpack('LLLHH', data[start:start+16])
147 crc32, comp_size, uncomp_size, filenamesize, extra_size = fields
148
149 start += 16
150 filename = data[start:start+filenamesize]
151 start += filenamesize
152 extra = data[start:start+extra_size]
Georg Brandl6911e3c2007-09-04 07:15:32 +0000153 print(filename, hex(crc32), comp_size, uncomp_size)
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155 start += extra_size + comp_size # skip to the next header
156
157
158.. _tut-multi-threading:
159
160Multi-threading
161===============
162
163Threading is a technique for decoupling tasks which are not sequentially
164dependent. Threads can be used to improve the responsiveness of applications
165that accept user input while other tasks run in the background. A related use
166case is running I/O in parallel with computations in another thread.
167
168The following code shows how the high level :mod:`threading` module can run
169tasks in background while the main program continues to run::
170
171 import threading, zipfile
172
173 class AsyncZip(threading.Thread):
174 def __init__(self, infile, outfile):
175 threading.Thread.__init__(self)
176 self.infile = infile
177 self.outfile = outfile
178 def run(self):
179 f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
180 f.write(self.infile)
181 f.close()
Georg Brandle4ac7502007-09-03 07:10:24 +0000182 print('Finished background zip of:', self.infile)
Georg Brandl116aa622007-08-15 14:28:22 +0000183
184 background = AsyncZip('mydata.txt', 'myarchive.zip')
185 background.start()
Guido van Rossum0616b792007-08-31 03:25:11 +0000186 print('The main program continues to run in foreground.')
Georg Brandl116aa622007-08-15 14:28:22 +0000187
188 background.join() # Wait for the background task to finish
Guido van Rossum0616b792007-08-31 03:25:11 +0000189 print('Main program waited until background was done.')
Georg Brandl116aa622007-08-15 14:28:22 +0000190
191The principal challenge of multi-threaded applications is coordinating threads
192that share data or other resources. To that end, the threading module provides
193a number of synchronization primitives including locks, events, condition
194variables, and semaphores.
195
196While those tools are powerful, minor design errors can result in problems that
197are difficult to reproduce. So, the preferred approach to task coordination is
198to concentrate all access to a resource in a single thread and then use the
199:mod:`Queue` module to feed that thread with requests from other threads.
200Applications using :class:`Queue` objects for inter-thread communication and
201coordination are easier to design, more readable, and more reliable.
202
203
204.. _tut-logging:
205
206Logging
207=======
208
209The :mod:`logging` module offers a full featured and flexible logging system.
210At its simplest, log messages are sent to a file or to ``sys.stderr``::
211
212 import logging
213 logging.debug('Debugging information')
214 logging.info('Informational message')
215 logging.warning('Warning:config file %s not found', 'server.conf')
216 logging.error('Error occurred')
217 logging.critical('Critical error -- shutting down')
218
219This produces the following output::
220
221 WARNING:root:Warning:config file server.conf not found
222 ERROR:root:Error occurred
223 CRITICAL:root:Critical error -- shutting down
224
225By default, informational and debugging messages are suppressed and the output
226is sent to standard error. Other output options include routing messages
227through email, datagrams, sockets, or to an HTTP Server. New filters can select
228different routing based on message priority: :const:`DEBUG`, :const:`INFO`,
229:const:`WARNING`, :const:`ERROR`, and :const:`CRITICAL`.
230
231The logging system can be configured directly from Python or can be loaded from
232a user editable configuration file for customized logging without altering the
233application.
234
235
236.. _tut-weak-references:
237
238Weak References
239===============
240
241Python does automatic memory management (reference counting for most objects and
Christian Heimesd8654cf2007-12-02 15:22:16 +0000242:term:`garbage collection` to eliminate cycles). The memory is freed shortly
243after the last reference to it has been eliminated.
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245This approach works fine for most applications but occasionally there is a need
246to track objects only as long as they are being used by something else.
247Unfortunately, just tracking them creates a reference that makes them permanent.
248The :mod:`weakref` module provides tools for tracking objects without creating a
249reference. When the object is no longer needed, it is automatically removed
250from a weakref table and a callback is triggered for weakref objects. Typical
251applications include caching objects that are expensive to create::
252
253 >>> import weakref, gc
254 >>> class A:
255 ... def __init__(self, value):
256 ... self.value = value
257 ... def __repr__(self):
258 ... return str(self.value)
259 ...
260 >>> a = A(10) # create a reference
261 >>> d = weakref.WeakValueDictionary()
262 >>> d['primary'] = a # does not create a reference
263 >>> d['primary'] # fetch the object if it is still alive
264 10
265 >>> del a # remove the one reference
266 >>> gc.collect() # run garbage collection right away
267 0
268 >>> d['primary'] # entry was automatically removed
269 Traceback (most recent call last):
270 File "<pyshell#108>", line 1, in -toplevel-
271 d['primary'] # entry was automatically removed
272 File "C:/python30/lib/weakref.py", line 46, in __getitem__
273 o = self.data[key]()
274 KeyError: 'primary'
275
276
277.. _tut-list-tools:
278
279Tools for Working with Lists
280============================
281
282Many data structure needs can be met with the built-in list type. However,
283sometimes there is a need for alternative implementations with different
284performance trade-offs.
285
286The :mod:`array` module provides an :class:`array()` object that is like a list
287that stores only homogenous data and stores it more compactly. The following
288example shows an array of numbers stored as two byte unsigned binary numbers
289(typecode ``"H"``) rather than the usual 16 bytes per entry for regular lists of
290python int objects::
291
292 >>> from array import array
293 >>> a = array('H', [4000, 10, 700, 22222])
294 >>> sum(a)
295 26932
296 >>> a[1:3]
297 array('H', [10, 700])
298
299The :mod:`collections` module provides a :class:`deque()` object that is like a
300list with faster appends and pops from the left side but slower lookups in the
301middle. These objects are well suited for implementing queues and breadth first
302tree searches::
303
304 >>> from collections import deque
305 >>> d = deque(["task1", "task2", "task3"])
306 >>> d.append("task4")
Guido van Rossum0616b792007-08-31 03:25:11 +0000307 >>> print("Handling", d.popleft())
Georg Brandl116aa622007-08-15 14:28:22 +0000308 Handling task1
309
310 unsearched = deque([starting_node])
311 def breadth_first_search(unsearched):
312 node = unsearched.popleft()
313 for m in gen_moves(node):
314 if is_goal(m):
315 return m
316 unsearched.append(m)
317
318In addition to alternative list implementations, the library also offers other
319tools such as the :mod:`bisect` module with functions for manipulating sorted
320lists::
321
322 >>> import bisect
323 >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
324 >>> bisect.insort(scores, (300, 'ruby'))
325 >>> scores
326 [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
327
328The :mod:`heapq` module provides functions for implementing heaps based on
329regular lists. The lowest valued entry is always kept at position zero. This
330is useful for applications which repeatedly access the smallest element but do
331not want to run a full list sort::
332
333 >>> from heapq import heapify, heappop, heappush
334 >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
335 >>> heapify(data) # rearrange the list into heap order
336 >>> heappush(data, -5) # add a new entry
337 >>> [heappop(data) for i in range(3)] # fetch the three smallest entries
338 [-5, 0, 1]
339
340
341.. _tut-decimal-fp:
342
343Decimal Floating Point Arithmetic
344=================================
345
346The :mod:`decimal` module offers a :class:`Decimal` datatype for decimal
347floating point arithmetic. Compared to the built-in :class:`float`
348implementation of binary floating point, the new class is especially helpful for
349financial applications and other uses which require exact decimal
350representation, control over precision, control over rounding to meet legal or
351regulatory requirements, tracking of significant decimal places, or for
352applications where the user expects the results to match calculations done by
353hand.
354
355For example, calculating a 5% tax on a 70 cent phone charge gives different
356results in decimal floating point and binary floating point. The difference
357becomes significant if the results are rounded to the nearest cent::
358
359 >>> from decimal import *
360 >>> Decimal('0.70') * Decimal('1.05')
361 Decimal("0.7350")
362 >>> .70 * 1.05
363 0.73499999999999999
364
365The :class:`Decimal` result keeps a trailing zero, automatically inferring four
366place significance from multiplicands with two place significance. Decimal
367reproduces mathematics as done by hand and avoids issues that can arise when
368binary floating point cannot exactly represent decimal quantities.
369
370Exact representation enables the :class:`Decimal` class to perform modulo
371calculations and equality tests that are unsuitable for binary floating point::
372
373 >>> Decimal('1.00') % Decimal('.10')
374 Decimal("0.00")
375 >>> 1.00 % 0.10
376 0.09999999999999995
377
378 >>> sum([Decimal('0.1')]*10) == Decimal('1.0')
379 True
380 >>> sum([0.1]*10) == 1.0
381 False
382
383The :mod:`decimal` module provides arithmetic with as much precision as needed::
384
385 >>> getcontext().prec = 36
386 >>> Decimal(1) / Decimal(7)
387 Decimal("0.142857142857142857142857142857142857")
388
389