blob: c0197ea5ef8cf92bbc69c8ceb46af9456c27e09f [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
Alexandre Vassalotti1f2ba4b2008-05-16 07:12:44 +000016The :mod:`reprlib` module provides a version of :func:`repr` customized for
Georg Brandl116aa622007-08-15 14:28:22 +000017abbreviated displays of large or deeply nested containers::
18
Alexandre Vassalotti1f2ba4b2008-05-16 07:12:44 +000019 >>> import reprlib
20 >>> reprlib.repr(set('supercalifragilisticexpialidocious'))
Georg Brandl116aa622007-08-15 14:28:22 +000021 "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'
Georg Brandl4a52a4c2009-08-13 12:06:43 +000064 >>> locale.format_string("%s%.*f", (conv['currency_symbol'],
65 ... conv['frac_digits'], x), grouping=True)
Georg Brandl116aa622007-08-15 14:28:22 +000066 '$1,234,567.80'
67
68
69.. _tut-templating:
70
71Templating
72==========
73
Serhiy Storchaka91aaeac2013-10-09 09:54:46 +030074The :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.
Georg Brandl116aa622007-08-15 14:28:22 +000077
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
Serhiy Storchaka91aaeac2013-10-09 09:54:46 +030088The :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::
Georg Brandl116aa622007-08-15 14:28:22 +000093
94 >>> t = Template('Return the $item to $owner.')
95 >>> d = dict(item='unladen swallow')
96 >>> t.substitute(d)
97 Traceback (most recent call last):
Ezio Melotti8618fb62012-09-24 17:30:39 +030098 ...
Georg Brandl116aa622007-08-15 14:28:22 +000099 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)
Benjamin Petersone6f00632008-05-26 01:03:56 +0000119 ... print('{0} --> {1}'.format(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
Serhiy Storchaka91aaeac2013-10-09 09:54:46 +0300135The :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
Christian Heimese7a15bb2008-01-24 16:21:45 +0000138how to loop through header information in a ZIP file without using the
139:mod:`zipfile` module. Pack codes ``"H"`` and ``"I"`` represent two and four
140byte unsigned numbers respectively. The ``"<"`` indicates that they are
141standard size and in little-endian byte order::
Georg Brandl116aa622007-08-15 14:28:22 +0000142
143 import struct
144
Éric Araujoa3dd56b2011-03-11 17:42:48 +0100145 with open('myfile.zip', 'rb') as f:
146 data = f.read()
147
Georg Brandl116aa622007-08-15 14:28:22 +0000148 start = 0
149 for i in range(3): # show the first 3 file headers
150 start += 14
Christian Heimese7a15bb2008-01-24 16:21:45 +0000151 fields = struct.unpack('<IIIHH', data[start:start+16])
Georg Brandl116aa622007-08-15 14:28:22 +0000152 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]
Georg Brandl6911e3c2007-09-04 07:15:32 +0000158 print(filename, hex(crc32), comp_size, uncomp_size)
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160 start += extra_size + comp_size # skip to the next header
161
162
163.. _tut-multi-threading:
164
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
173The following code shows how the high level :mod:`threading` module can run
174tasks in background while the main program continues to run::
175
176 import threading, zipfile
177
178 class AsyncZip(threading.Thread):
179 def __init__(self, infile, outfile):
Georg Brandl48310cd2009-01-03 21:18:54 +0000180 threading.Thread.__init__(self)
Georg Brandl116aa622007-08-15 14:28:22 +0000181 self.infile = infile
182 self.outfile = outfile
183 def run(self):
184 f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
185 f.write(self.infile)
186 f.close()
Georg Brandle4ac7502007-09-03 07:10:24 +0000187 print('Finished background zip of:', self.infile)
Georg Brandl116aa622007-08-15 14:28:22 +0000188
189 background = AsyncZip('mydata.txt', 'myarchive.zip')
190 background.start()
Guido van Rossum0616b792007-08-31 03:25:11 +0000191 print('The main program continues to run in foreground.')
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193 background.join() # Wait for the background task to finish
Guido van Rossum0616b792007-08-31 03:25:11 +0000194 print('Main program waited until background was done.')
Georg Brandl116aa622007-08-15 14:28:22 +0000195
196The principal challenge of multi-threaded applications is coordinating threads
197that share data or other resources. To that end, the threading module provides
198a number of synchronization primitives including locks, events, condition
199variables, and semaphores.
200
201While those tools are powerful, minor design errors can result in problems that
202are difficult to reproduce. So, the preferred approach to task coordination is
203to concentrate all access to a resource in a single thread and then use the
Alexandre Vassalottif260e442008-05-11 19:59:59 +0000204:mod:`queue` module to feed that thread with requests from other threads.
Serhiy Storchaka91aaeac2013-10-09 09:54:46 +0300205Applications using :class:`~queue.Queue` objects for inter-thread communication and
Georg Brandl116aa622007-08-15 14:28:22 +0000206coordination are easier to design, more readable, and more reliable.
207
208
209.. _tut-logging:
210
211Logging
212=======
213
214The :mod:`logging` module offers a full featured and flexible logging system.
215At its simplest, log messages are sent to a file or to ``sys.stderr``::
216
217 import logging
218 logging.debug('Debugging information')
219 logging.info('Informational message')
220 logging.warning('Warning:config file %s not found', 'server.conf')
221 logging.error('Error occurred')
222 logging.critical('Critical error -- shutting down')
223
Ezio Melotti8618fb62012-09-24 17:30:39 +0300224This produces the following output:
225
226.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000227
228 WARNING:root:Warning:config file server.conf not found
229 ERROR:root:Error occurred
230 CRITICAL:root:Critical error -- shutting down
231
232By default, informational and debugging messages are suppressed and the output
233is sent to standard error. Other output options include routing messages
234through email, datagrams, sockets, or to an HTTP Server. New filters can select
Serhiy Storchaka91aaeac2013-10-09 09:54:46 +0300235different routing based on message priority: :const:`~logging.DEBUG`,
236:const:`~logging.INFO`, :const:`~logging.WARNING`, :const:`~logging.ERROR`,
237and :const:`~logging.CRITICAL`.
Georg Brandl116aa622007-08-15 14:28:22 +0000238
239The logging system can be configured directly from Python or can be loaded from
240a user editable configuration file for customized logging without altering the
241application.
242
243
244.. _tut-weak-references:
245
246Weak References
247===============
248
249Python does automatic memory management (reference counting for most objects and
Christian Heimesd8654cf2007-12-02 15:22:16 +0000250:term:`garbage collection` to eliminate cycles). The memory is freed shortly
251after the last reference to it has been eliminated.
Georg Brandl116aa622007-08-15 14:28:22 +0000252
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.
256The :mod:`weakref` module provides tools for tracking objects without creating a
257reference. When the object is no longer needed, it is automatically removed
258from a weakref table and a callback is triggered for weakref objects. Typical
259applications include caching objects that are expensive to create::
260
261 >>> import weakref, gc
262 >>> class A:
263 ... def __init__(self, value):
Jesus Ceaaf387742012-10-22 13:15:17 +0200264 ... self.value = value
Georg Brandl116aa622007-08-15 14:28:22 +0000265 ... def __repr__(self):
Jesus Ceaaf387742012-10-22 13:15:17 +0200266 ... return str(self.value)
Georg Brandl116aa622007-08-15 14:28:22 +0000267 ...
268 >>> a = A(10) # create a reference
269 >>> d = weakref.WeakValueDictionary()
270 >>> d['primary'] = a # does not create a reference
271 >>> d['primary'] # fetch the object if it is still alive
272 10
273 >>> del a # remove the one reference
274 >>> gc.collect() # run garbage collection right away
275 0
276 >>> d['primary'] # entry was automatically removed
277 Traceback (most recent call last):
Christian Heimesc3f30c42008-02-22 16:37:40 +0000278 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000279 d['primary'] # entry was automatically removed
Georg Brandl08a90122012-09-29 09:34:13 +0200280 File "C:/python34/lib/weakref.py", line 46, in __getitem__
Georg Brandl116aa622007-08-15 14:28:22 +0000281 o = self.data[key]()
282 KeyError: 'primary'
283
284
285.. _tut-list-tools:
286
287Tools for Working with Lists
288============================
289
290Many data structure needs can be met with the built-in list type. However,
291sometimes there is a need for alternative implementations with different
292performance trade-offs.
293
Serhiy Storchaka91aaeac2013-10-09 09:54:46 +0300294The :mod:`array` module provides an :class:`~array.array()` object that is like
295a list that stores only homogeneous data and stores it more compactly. The
296following example shows an array of numbers stored as two byte unsigned binary
297numbers (typecode ``"H"``) rather than the usual 16 bytes per entry for regular
298lists of Python int objects::
Georg Brandl116aa622007-08-15 14:28:22 +0000299
300 >>> from array import array
301 >>> a = array('H', [4000, 10, 700, 22222])
302 >>> sum(a)
303 26932
304 >>> a[1:3]
305 array('H', [10, 700])
306
Serhiy Storchaka91aaeac2013-10-09 09:54:46 +0300307The :mod:`collections` module provides a :class:`~collections.deque()` object
308that is like a list with faster appends and pops from the left side but slower
309lookups in the middle. These objects are well suited for implementing queues
310and breadth first tree searches::
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312 >>> from collections import deque
313 >>> d = deque(["task1", "task2", "task3"])
314 >>> d.append("task4")
Guido van Rossum0616b792007-08-31 03:25:11 +0000315 >>> print("Handling", d.popleft())
Georg Brandl116aa622007-08-15 14:28:22 +0000316 Handling task1
317
Ezio Melotti8618fb62012-09-24 17:30:39 +0300318::
319
Georg Brandl116aa622007-08-15 14:28:22 +0000320 unsearched = deque([starting_node])
321 def breadth_first_search(unsearched):
322 node = unsearched.popleft()
323 for m in gen_moves(node):
324 if is_goal(m):
325 return m
326 unsearched.append(m)
327
328In addition to alternative list implementations, the library also offers other
329tools such as the :mod:`bisect` module with functions for manipulating sorted
330lists::
331
332 >>> import bisect
333 >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
334 >>> bisect.insort(scores, (300, 'ruby'))
335 >>> scores
336 [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]
337
338The :mod:`heapq` module provides functions for implementing heaps based on
339regular lists. The lowest valued entry is always kept at position zero. This
340is useful for applications which repeatedly access the smallest element but do
341not want to run a full list sort::
342
343 >>> from heapq import heapify, heappop, heappush
344 >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
345 >>> heapify(data) # rearrange the list into heap order
346 >>> heappush(data, -5) # add a new entry
347 >>> [heappop(data) for i in range(3)] # fetch the three smallest entries
348 [-5, 0, 1]
349
350
351.. _tut-decimal-fp:
352
353Decimal Floating Point Arithmetic
354=================================
355
Serhiy Storchaka91aaeac2013-10-09 09:54:46 +0300356The :mod:`decimal` module offers a :class:`~decimal.Decimal` datatype for
357decimal floating point arithmetic. Compared to the built-in :class:`float`
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000358implementation of binary floating point, the class is especially helpful for
359
360* financial applications and other uses which require exact decimal
361 representation,
362* control over precision,
363* control over rounding to meet legal or regulatory requirements,
364* tracking of significant decimal places, or
365* applications where the user expects the results to match calculations done by
366 hand.
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368For example, calculating a 5% tax on a 70 cent phone charge gives different
369results in decimal floating point and binary floating point. The difference
370becomes significant if the results are rounded to the nearest cent::
371
Georg Brandl48310cd2009-01-03 21:18:54 +0000372 >>> from decimal import *
Mark Dickinson5a55b612009-06-28 20:59:42 +0000373 >>> round(Decimal('0.70') * Decimal('1.05'), 2)
374 Decimal('0.74')
375 >>> round(.70 * 1.05, 2)
376 0.73
Georg Brandl116aa622007-08-15 14:28:22 +0000377
Serhiy Storchaka91aaeac2013-10-09 09:54:46 +0300378The :class:`~decimal.Decimal` result keeps a trailing zero, automatically
379inferring four place significance from multiplicands with two place
380significance. Decimal reproduces mathematics as done by hand and avoids
381issues that can arise when binary floating point cannot exactly represent
382decimal quantities.
Georg Brandl116aa622007-08-15 14:28:22 +0000383
Serhiy Storchaka91aaeac2013-10-09 09:54:46 +0300384Exact representation enables the :class:`~decimal.Decimal` class to perform
385modulo calculations and equality tests that are unsuitable for binary floating
386point::
Georg Brandl116aa622007-08-15 14:28:22 +0000387
388 >>> Decimal('1.00') % Decimal('.10')
Mark Dickinson2c02bdc2009-06-28 21:24:42 +0000389 Decimal('0.00')
Georg Brandl116aa622007-08-15 14:28:22 +0000390 >>> 1.00 % 0.10
391 0.09999999999999995
392
393 >>> sum([Decimal('0.1')]*10) == Decimal('1.0')
394 True
395 >>> sum([0.1]*10) == 1.0
Georg Brandl48310cd2009-01-03 21:18:54 +0000396 False
Georg Brandl116aa622007-08-15 14:28:22 +0000397
398The :mod:`decimal` module provides arithmetic with as much precision as needed::
399
400 >>> getcontext().prec = 36
401 >>> Decimal(1) / Decimal(7)
Mark Dickinson2c02bdc2009-06-28 21:24:42 +0000402 Decimal('0.142857142857142857142857142857142857')
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404