Commit | Line | Data |
---|---|---|
920dae64 AT |
1 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> |
2 | <html> | |
3 | <head> | |
4 | <link rel="STYLESHEET" href="tut.css" type='text/css' /> | |
5 | <link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" /> | |
6 | <link rel='start' href='../index.html' title='Python Documentation Index' /> | |
7 | <link rel="first" href="tut.html" title='Python Tutorial' /> | |
8 | <link rel='contents' href='node2.html' title="Contents" /> | |
9 | <link rel='index' href='node19.html' title='Index' /> | |
10 | <link rel='last' href='about.html' title='About this document...' /> | |
11 | <link rel='help' href='about.html' title='About this document...' /> | |
12 | <link rel="next" href="node14.html" /> | |
13 | <link rel="prev" href="node12.html" /> | |
14 | <link rel="parent" href="tut.html" /> | |
15 | <link rel="next" href="node14.html" /> | |
16 | <meta name='aesop' content='information' /> | |
17 | <title>11. Brief Tour of the Standard Library - Part II</title> | |
18 | </head> | |
19 | <body> | |
20 | <DIV CLASS="navigation"> | |
21 | <div id='top-navigation-panel' xml:id='top-navigation-panel'> | |
22 | <table align="center" width="100%" cellpadding="0" cellspacing="2"> | |
23 | <tr> | |
24 | <td class='online-navigation'><a rel="prev" title="10. Brief Tour of" | |
25 | href="node12.html"><img src='../icons/previous.png' | |
26 | border='0' height='32' alt='Previous Page' width='32' /></A></td> | |
27 | <td class='online-navigation'><a rel="parent" title="Python Tutorial" | |
28 | href="tut.html"><img src='../icons/up.png' | |
29 | border='0' height='32' alt='Up One Level' width='32' /></A></td> | |
30 | <td class='online-navigation'><a rel="next" title="12. What Now?" | |
31 | href="node14.html"><img src='../icons/next.png' | |
32 | border='0' height='32' alt='Next Page' width='32' /></A></td> | |
33 | <td align="center" width="100%">Python Tutorial</td> | |
34 | <td class='online-navigation'><a rel="contents" title="Table of Contents" | |
35 | href="node2.html"><img src='../icons/contents.png' | |
36 | border='0' height='32' alt='Contents' width='32' /></A></td> | |
37 | <td class='online-navigation'><img src='../icons/blank.png' | |
38 | border='0' height='32' alt='' width='32' /></td> | |
39 | <td class='online-navigation'><a rel="index" title="Index" | |
40 | href="node19.html"><img src='../icons/index.png' | |
41 | border='0' height='32' alt='Index' width='32' /></A></td> | |
42 | </tr></table> | |
43 | <div class='online-navigation'> | |
44 | <b class="navlabel">Previous:</b> | |
45 | <a class="sectref" rel="prev" href="node12.html">10. Brief Tour of</A> | |
46 | <b class="navlabel">Up:</b> | |
47 | <a class="sectref" rel="parent" href="tut.html">Python Tutorial</A> | |
48 | <b class="navlabel">Next:</b> | |
49 | <a class="sectref" rel="next" href="node14.html">12. What Now?</A> | |
50 | </div> | |
51 | <hr /></div> | |
52 | </DIV> | |
53 | <!--End of Navigation Panel--> | |
54 | <div class='online-navigation'> | |
55 | <!--Table of Child-Links--> | |
56 | <A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a> | |
57 | ||
58 | <UL CLASS="ChildLinks"> | |
59 | <LI><A href="node13.html#SECTION0013100000000000000000">11.1 Output Formatting</a> | |
60 | <LI><A href="node13.html#SECTION0013200000000000000000">11.2 Templating</a> | |
61 | <LI><A href="node13.html#SECTION0013300000000000000000">11.3 Working with Binary Data Record Layouts</a> | |
62 | <LI><A href="node13.html#SECTION0013400000000000000000">11.4 Multi-threading</a> | |
63 | <LI><A href="node13.html#SECTION0013500000000000000000">11.5 Logging</a> | |
64 | <LI><A href="node13.html#SECTION0013600000000000000000">11.6 Weak References</a> | |
65 | <LI><A href="node13.html#SECTION0013700000000000000000">11.7 Tools for Working with Lists</a> | |
66 | <LI><A href="node13.html#SECTION0013800000000000000000">11.8 Decimal Floating Point Arithmetic</a> | |
67 | </ul> | |
68 | <!--End of Table of Child-Links--> | |
69 | </div> | |
70 | <HR> | |
71 | ||
72 | <H1><A NAME="SECTION0013000000000000000000"></A><A NAME="briefTourTwo"></A> | |
73 | <BR> | |
74 | 11. Brief Tour of the Standard Library - Part II | |
75 | </H1> | |
76 | ||
77 | <P> | |
78 | This second tour covers more advanced modules that support professional | |
79 | programming needs. These modules rarely occur in small scripts. | |
80 | ||
81 | <P> | |
82 | ||
83 | <H1><A NAME="SECTION0013100000000000000000"></A><A NAME="output-formatting"></A> | |
84 | <BR> | |
85 | 11.1 Output Formatting | |
86 | </H1> | |
87 | ||
88 | <P> | |
89 | The <a class="ulink" href="../lib/module-repr.html" | |
90 | ><tt class="module">repr</tt></a> module provides an | |
91 | version of <tt class="function">repr()</tt> for abbreviated displays of large or deeply | |
92 | nested containers: | |
93 | ||
94 | <P> | |
95 | <div class="verbatim"><pre> | |
96 | >>> import repr | |
97 | >>> repr.repr(set('supercalifragilisticexpialidocious')) | |
98 | "set(['a', 'c', 'd', 'e', 'f', 'g', ...])" | |
99 | </pre></div> | |
100 | ||
101 | <P> | |
102 | The <a class="ulink" href="../lib/module-pprint.html" | |
103 | ><tt class="module">pprint</tt></a> module offers | |
104 | more sophisticated control over printing both built-in and user defined | |
105 | objects in a way that is readable by the interpreter. When the result | |
106 | is longer than one line, the ``pretty printer'' adds line breaks and | |
107 | indentation to more clearly reveal data structure: | |
108 | ||
109 | <P> | |
110 | <div class="verbatim"><pre> | |
111 | >>> import pprint | |
112 | >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', | |
113 | ... 'yellow'], 'blue']]] | |
114 | ... | |
115 | >>> pprint.pprint(t, width=30) | |
116 | [[[['black', 'cyan'], | |
117 | 'white', | |
118 | ['green', 'red']], | |
119 | [['magenta', 'yellow'], | |
120 | 'blue']]] | |
121 | </pre></div> | |
122 | ||
123 | <P> | |
124 | The <a class="ulink" href="../lib/module-textwrap.html" | |
125 | ><tt class="module">textwrap</tt></a> module | |
126 | formats paragraphs of text to fit a given screen width: | |
127 | ||
128 | <P> | |
129 | <div class="verbatim"><pre> | |
130 | >>> import textwrap | |
131 | >>> doc = """The wrap() method is just like fill() except that it returns | |
132 | ... a list of strings instead of one big string with newlines to separate | |
133 | ... the wrapped lines.""" | |
134 | ... | |
135 | >>> print textwrap.fill(doc, width=40) | |
136 | The wrap() method is just like fill() | |
137 | except that it returns a list of strings | |
138 | instead of one big string with newlines | |
139 | to separate the wrapped lines. | |
140 | </pre></div> | |
141 | ||
142 | <P> | |
143 | The <a class="ulink" href="../lib/module-locale.html" | |
144 | ><tt class="module">locale</tt></a> module accesses | |
145 | a database of culture specific data formats. The grouping attribute | |
146 | of locale's format function provides a direct way of formatting numbers | |
147 | with group separators: | |
148 | ||
149 | <P> | |
150 | <div class="verbatim"><pre> | |
151 | >>> import locale | |
152 | >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252') | |
153 | 'English_United States.1252' | |
154 | >>> conv = locale.localeconv() # get a mapping of conventions | |
155 | >>> x = 1234567.8 | |
156 | >>> locale.format("%d", x, grouping=True) | |
157 | '1,234,567' | |
158 | >>> locale.format("%s%.*f", (conv['currency_symbol'], | |
159 | ... conv['frac_digits'], x), grouping=True) | |
160 | '$1,234,567.80' | |
161 | </pre></div> | |
162 | ||
163 | <P> | |
164 | ||
165 | <H1><A NAME="SECTION0013200000000000000000"></A><A NAME="templating"></A> | |
166 | <BR> | |
167 | 11.2 Templating | |
168 | </H1> | |
169 | ||
170 | <P> | |
171 | The <a class="ulink" href="../lib/module-string.html" | |
172 | ><tt class="module">string</tt></a> module includes a | |
173 | versatile <tt class="class">Template</tt> class with a simplified syntax suitable for | |
174 | editing by end-users. This allows users to customize their applications | |
175 | without having to alter the application. | |
176 | ||
177 | <P> | |
178 | The format uses placeholder names formed by "<tt class="samp">$</tt>" with valid Python | |
179 | identifiers (alphanumeric characters and underscores). Surrounding the | |
180 | placeholder with braces allows it to be followed by more alphanumeric letters | |
181 | with no intervening spaces. Writing "<tt class="samp">$$</tt>" creates a single escaped | |
182 | "<tt class="samp">$</tt>": | |
183 | ||
184 | <P> | |
185 | <div class="verbatim"><pre> | |
186 | >>> from string import Template | |
187 | >>> t = Template('${village}folk send $$10 to $cause.') | |
188 | >>> t.substitute(village='Nottingham', cause='the ditch fund') | |
189 | 'Nottinghamfolk send $10 to the ditch fund.' | |
190 | </pre></div> | |
191 | ||
192 | <P> | |
193 | The <tt class="method">substitute</tt> method raises a <tt class="exception">KeyError</tt> when a | |
194 | placeholder is not supplied in a dictionary or a keyword argument. For | |
195 | mail-merge style applications, user supplied data may be incomplete and the | |
196 | <tt class="method">safe_substitute</tt> method may be more appropriate -- it will leave | |
197 | placeholders unchanged if data is missing: | |
198 | ||
199 | <P> | |
200 | <div class="verbatim"><pre> | |
201 | >>> t = Template('Return the $item to $owner.') | |
202 | >>> d = dict(item='unladen swallow') | |
203 | >>> t.substitute(d) | |
204 | Traceback (most recent call last): | |
205 | . . . | |
206 | KeyError: 'owner' | |
207 | >>> t.safe_substitute(d) | |
208 | 'Return the unladen swallow to $owner.' | |
209 | </pre></div> | |
210 | ||
211 | <P> | |
212 | Template subclasses can specify a custom delimiter. For example, a batch | |
213 | renaming utility for a photo browser may elect to use percent signs for | |
214 | placeholders such as the current date, image sequence number, or file format: | |
215 | ||
216 | <P> | |
217 | <div class="verbatim"><pre> | |
218 | >>> import time, os.path | |
219 | >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg'] | |
220 | >>> class BatchRename(Template): | |
221 | ... delimiter = '%' | |
222 | >>> fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format): ') | |
223 | Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f | |
224 | ||
225 | >>> t = BatchRename(fmt) | |
226 | >>> date = time.strftime('%d%b%y') | |
227 | >>> for i, filename in enumerate(photofiles): | |
228 | ... base, ext = os.path.splitext(filename) | |
229 | ... newname = t.substitute(d=date, n=i, f=ext) | |
230 | ... print '%s --> %s' % (filename, newname) | |
231 | ||
232 | img_1074.jpg --> Ashley_0.jpg | |
233 | img_1076.jpg --> Ashley_1.jpg | |
234 | img_1077.jpg --> Ashley_2.jpg | |
235 | </pre></div> | |
236 | ||
237 | <P> | |
238 | Another application for templating is separating program logic from the | |
239 | details of multiple output formats. This makes it possible to substitute | |
240 | custom templates for XML files, plain text reports, and HTML web reports. | |
241 | ||
242 | <P> | |
243 | ||
244 | <H1><A NAME="SECTION0013300000000000000000"></A><A NAME="binary-formats"></A> | |
245 | <BR> | |
246 | 11.3 Working with Binary Data Record Layouts | |
247 | </H1> | |
248 | ||
249 | <P> | |
250 | The <a class="ulink" href="../lib/module-struct.html" | |
251 | ><tt class="module">struct</tt></a> module provides | |
252 | <tt class="function">pack()</tt> and <tt class="function">unpack()</tt> functions for working with | |
253 | variable length binary record formats. The following example shows how | |
254 | to loop through header information in a ZIP file (with pack codes | |
255 | <code>"H"</code> and <code>"L"</code> representing two and four byte unsigned | |
256 | numbers respectively): | |
257 | ||
258 | <P> | |
259 | <div class="verbatim"><pre> | |
260 | import struct | |
261 | ||
262 | data = open('myfile.zip', 'rb').read() | |
263 | start = 0 | |
264 | for i in range(3): # show the first 3 file headers | |
265 | start += 14 | |
266 | fields = struct.unpack('LLLHH', data[start:start+16]) | |
267 | crc32, comp_size, uncomp_size, filenamesize, extra_size = fields | |
268 | ||
269 | start += 16 | |
270 | filename = data[start:start+filenamesize] | |
271 | start += filenamesize | |
272 | extra = data[start:start+extra_size] | |
273 | print filename, hex(crc32), comp_size, uncomp_size | |
274 | ||
275 | start += extra_size + comp_size # skip to the next header | |
276 | </pre></div> | |
277 | ||
278 | <P> | |
279 | ||
280 | <H1><A NAME="SECTION0013400000000000000000"></A><A NAME="multi-threading"></A> | |
281 | <BR> | |
282 | 11.4 Multi-threading | |
283 | </H1> | |
284 | ||
285 | <P> | |
286 | Threading is a technique for decoupling tasks which are not sequentially | |
287 | dependent. Threads can be used to improve the responsiveness of | |
288 | applications that accept user input while other tasks run in the | |
289 | background. A related use case is running I/O in parallel with | |
290 | computations in another thread. | |
291 | ||
292 | <P> | |
293 | The following code shows how the high level | |
294 | <a class="ulink" href="../lib/module-threading.html" | |
295 | ><tt class="module">threading</tt></a> module can run | |
296 | tasks in background while the main program continues to run: | |
297 | ||
298 | <P> | |
299 | <div class="verbatim"><pre> | |
300 | import threading, zipfile | |
301 | ||
302 | class AsyncZip(threading.Thread): | |
303 | def __init__(self, infile, outfile): | |
304 | threading.Thread.__init__(self) | |
305 | self.infile = infile | |
306 | self.outfile = outfile | |
307 | def run(self): | |
308 | f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) | |
309 | f.write(self.infile) | |
310 | f.close() | |
311 | print 'Finished background zip of: ', self.infile | |
312 | ||
313 | background = AsyncZip('mydata.txt', 'myarchive.zip') | |
314 | background.start() | |
315 | print 'The main program continues to run in foreground.' | |
316 | ||
317 | background.join() # Wait for the background task to finish | |
318 | print 'Main program waited until background was done.' | |
319 | </pre></div> | |
320 | ||
321 | <P> | |
322 | The principal challenge of multi-threaded applications is coordinating | |
323 | threads that share data or other resources. To that end, the threading | |
324 | module provides a number of synchronization primitives including locks, | |
325 | events, condition variables, and semaphores. | |
326 | ||
327 | <P> | |
328 | While those tools are powerful, minor design errors can result in | |
329 | problems that are difficult to reproduce. So, the preferred approach | |
330 | to task coordination is to concentrate all access to a resource | |
331 | in a single thread and then use the | |
332 | <a class="ulink" href="../lib/module-Queue.html" | |
333 | ><tt class="module">Queue</tt></a> module to feed that | |
334 | thread with requests from other threads. Applications using | |
335 | <tt class="class">Queue</tt> objects for inter-thread communication and coordination | |
336 | are easier to design, more readable, and more reliable. | |
337 | ||
338 | <P> | |
339 | ||
340 | <H1><A NAME="SECTION0013500000000000000000"></A><A NAME="logging"></A> | |
341 | <BR> | |
342 | 11.5 Logging | |
343 | </H1> | |
344 | ||
345 | <P> | |
346 | The <a class="ulink" href="../lib/module-logging.html" | |
347 | ><tt class="module">logging</tt></a> module offers | |
348 | a full featured and flexible logging system. At its simplest, log | |
349 | messages are sent to a file or to <code>sys.stderr</code>: | |
350 | ||
351 | <P> | |
352 | <div class="verbatim"><pre> | |
353 | import logging | |
354 | logging.debug('Debugging information') | |
355 | logging.info('Informational message') | |
356 | logging.warning('Warning:config file %s not found', 'server.conf') | |
357 | logging.error('Error occurred') | |
358 | logging.critical('Critical error -- shutting down') | |
359 | </pre></div> | |
360 | ||
361 | <P> | |
362 | This produces the following output: | |
363 | ||
364 | <P> | |
365 | <div class="verbatim"><pre> | |
366 | WARNING:root:Warning:config file server.conf not found | |
367 | ERROR:root:Error occurred | |
368 | CRITICAL:root:Critical error -- shutting down | |
369 | </pre></div> | |
370 | ||
371 | <P> | |
372 | By default, informational and debugging messages are suppressed and the | |
373 | output is sent to standard error. Other output options include routing | |
374 | messages through email, datagrams, sockets, or to an HTTP Server. New | |
375 | filters can select different routing based on message priority: | |
376 | <tt class="constant">DEBUG</tt>, <tt class="constant">INFO</tt>, <tt class="constant">WARNING</tt>, <tt class="constant">ERROR</tt>, | |
377 | and <tt class="constant">CRITICAL</tt>. | |
378 | ||
379 | <P> | |
380 | The logging system can be configured directly from Python or can be | |
381 | loaded from a user editable configuration file for customized logging | |
382 | without altering the application. | |
383 | ||
384 | <P> | |
385 | ||
386 | <H1><A NAME="SECTION0013600000000000000000"></A><A NAME="weak-references"></A> | |
387 | <BR> | |
388 | 11.6 Weak References | |
389 | </H1> | |
390 | ||
391 | <P> | |
392 | Python does automatic memory management (reference counting for most | |
393 | objects and garbage collection to eliminate cycles). The memory is | |
394 | freed shortly after the last reference to it has been eliminated. | |
395 | ||
396 | <P> | |
397 | This approach works fine for most applications but occasionally there | |
398 | is a need to track objects only as long as they are being used by | |
399 | something else. Unfortunately, just tracking them creates a reference | |
400 | that makes them permanent. The | |
401 | <a class="ulink" href="../lib/module-weakref.html" | |
402 | ><tt class="module">weakref</tt></a> module provides | |
403 | tools for tracking objects without creating a reference. When the | |
404 | object is no longer needed, it is automatically removed from a weakref | |
405 | table and a callback is triggered for weakref objects. Typical | |
406 | applications include caching objects that are expensive to create: | |
407 | ||
408 | <P> | |
409 | <div class="verbatim"><pre> | |
410 | >>> import weakref, gc | |
411 | >>> class A: | |
412 | ... def __init__(self, value): | |
413 | ... self.value = value | |
414 | ... def __repr__(self): | |
415 | ... return str(self.value) | |
416 | ... | |
417 | >>> a = A(10) # create a reference | |
418 | >>> d = weakref.WeakValueDictionary() | |
419 | >>> d['primary'] = a # does not create a reference | |
420 | >>> d['primary'] # fetch the object if it is still alive | |
421 | 10 | |
422 | >>> del a # remove the one reference | |
423 | >>> gc.collect() # run garbage collection right away | |
424 | 0 | |
425 | >>> d['primary'] # entry was automatically removed | |
426 | Traceback (most recent call last): | |
427 | File "<pyshell#108>", line 1, in -toplevel- | |
428 | d['primary'] # entry was automatically removed | |
429 | File "C:/PY24/lib/weakref.py", line 46, in __getitem__ | |
430 | o = self.data[key]() | |
431 | KeyError: 'primary' | |
432 | </pre></div> | |
433 | ||
434 | <P> | |
435 | ||
436 | <H1><A NAME="SECTION0013700000000000000000"></A><A NAME="list-tools"></A> | |
437 | <BR> | |
438 | 11.7 Tools for Working with Lists | |
439 | </H1> | |
440 | ||
441 | <P> | |
442 | Many data structure needs can be met with the built-in list type. | |
443 | However, sometimes there is a need for alternative implementations | |
444 | with different performance trade-offs. | |
445 | ||
446 | <P> | |
447 | The <a class="ulink" href="../lib/module-array.html" | |
448 | ><tt class="module">array</tt></a> module provides an | |
449 | <tt class="class">array()</tt> object that is like a list that stores only homogenous | |
450 | data but stores it more compactly. The following example shows an array | |
451 | of numbers stored as two byte unsigned binary numbers (typecode | |
452 | <code>"H"</code>) rather than the usual 16 bytes per entry for regular lists | |
453 | of python int objects: | |
454 | ||
455 | <P> | |
456 | <div class="verbatim"><pre> | |
457 | >>> from array import array | |
458 | >>> a = array('H', [4000, 10, 700, 22222]) | |
459 | >>> sum(a) | |
460 | 26932 | |
461 | >>> a[1:3] | |
462 | array('H', [10, 700]) | |
463 | </pre></div> | |
464 | ||
465 | <P> | |
466 | The <a class="ulink" href="../lib/module-collections.html" | |
467 | ><tt class="module">collections</tt></a> module | |
468 | provides a <tt class="class">deque()</tt> object that is like a list with faster | |
469 | appends and pops from the left side but slower lookups in the middle. | |
470 | These objects are well suited for implementing queues and breadth first | |
471 | tree searches: | |
472 | ||
473 | <P> | |
474 | <div class="verbatim"><pre> | |
475 | >>> from collections import deque | |
476 | >>> d = deque(["task1", "task2", "task3"]) | |
477 | >>> d.append("task4") | |
478 | >>> print "Handling", d.popleft() | |
479 | Handling task1 | |
480 | ||
481 | unsearched = deque([starting_node]) | |
482 | def breadth_first_search(unsearched): | |
483 | node = unsearched.popleft() | |
484 | for m in gen_moves(node): | |
485 | if is_goal(m): | |
486 | return m | |
487 | unsearched.append(m) | |
488 | </pre></div> | |
489 | ||
490 | <P> | |
491 | In addition to alternative list implementations, the library also offers | |
492 | other tools such as the <a class="ulink" href="../lib/module-bisect.html" | |
493 | ><tt class="module">bisect</tt></a> | |
494 | module with functions for manipulating sorted lists: | |
495 | ||
496 | <P> | |
497 | <div class="verbatim"><pre> | |
498 | >>> import bisect | |
499 | >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')] | |
500 | >>> bisect.insort(scores, (300, 'ruby')) | |
501 | >>> scores | |
502 | [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')] | |
503 | </pre></div> | |
504 | ||
505 | <P> | |
506 | The <a class="ulink" href="../lib/module-heapq.html" | |
507 | ><tt class="module">heapq</tt></a> module provides | |
508 | functions for implementing heaps based on regular lists. The lowest | |
509 | valued entry is always kept at position zero. This is useful for | |
510 | applications which repeatedly access the smallest element but do not | |
511 | want to run a full list sort: | |
512 | ||
513 | <P> | |
514 | <div class="verbatim"><pre> | |
515 | >>> from heapq import heapify, heappop, heappush | |
516 | >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] | |
517 | >>> heapify(data) # rearrange the list into heap order | |
518 | >>> heappush(data, -5) # add a new entry | |
519 | >>> [heappop(data) for i in range(3)] # fetch the three smallest entries | |
520 | [-5, 0, 1] | |
521 | </pre></div> | |
522 | ||
523 | <P> | |
524 | ||
525 | <H1><A NAME="SECTION0013800000000000000000"></A><A NAME="decimal-fp"></A> | |
526 | <BR> | |
527 | 11.8 Decimal Floating Point Arithmetic | |
528 | </H1> | |
529 | ||
530 | <P> | |
531 | The <a class="ulink" href="../lib/module-decimal.html" | |
532 | ><tt class="module">decimal</tt></a> module offers a | |
533 | <tt class="class">Decimal</tt> datatype for decimal floating point arithmetic. Compared to | |
534 | the built-in <tt class="class">float</tt> implementation of binary floating point, the new | |
535 | class is especially helpful for financial applications and other uses which | |
536 | require exact decimal representation, control over precision, control over | |
537 | rounding to meet legal or regulatory requirements, tracking of significant | |
538 | decimal places, or for applications where the user expects the results to | |
539 | match calculations done by hand. | |
540 | ||
541 | <P> | |
542 | For example, calculating a 5% tax on a 70 cent phone charge gives | |
543 | different results in decimal floating point and binary floating point. | |
544 | The difference becomes significant if the results are rounded to the | |
545 | nearest cent: | |
546 | ||
547 | <P> | |
548 | <div class="verbatim"><pre> | |
549 | >>> from decimal import * | |
550 | >>> Decimal('0.70') * Decimal('1.05') | |
551 | Decimal("0.7350") | |
552 | >>> .70 * 1.05 | |
553 | 0.73499999999999999 | |
554 | </pre></div> | |
555 | ||
556 | <P> | |
557 | The <tt class="class">Decimal</tt> result keeps a trailing zero, automatically inferring four | |
558 | place significance from multiplicands with two place significance. Decimal reproduces | |
559 | mathematics as done by hand and avoids issues that can arise when binary | |
560 | floating point cannot exactly represent decimal quantities. | |
561 | ||
562 | <P> | |
563 | Exact representation enables the <tt class="class">Decimal</tt> class to perform | |
564 | modulo calculations and equality tests that are unsuitable for binary | |
565 | floating point: | |
566 | ||
567 | <P> | |
568 | <div class="verbatim"><pre> | |
569 | >>> Decimal('1.00') % Decimal('.10') | |
570 | Decimal("0.00") | |
571 | >>> 1.00 % 0.10 | |
572 | 0.09999999999999995 | |
573 | ||
574 | >>> sum([Decimal('0.1')]*10) == Decimal('1.0') | |
575 | True | |
576 | >>> sum([0.1]*10) == 1.0 | |
577 | False | |
578 | </pre></div> | |
579 | ||
580 | <P> | |
581 | The <tt class="module">decimal</tt> module provides arithmetic with as much precision as | |
582 | needed: | |
583 | ||
584 | <P> | |
585 | <div class="verbatim"><pre> | |
586 | >>> getcontext().prec = 36 | |
587 | >>> Decimal(1) / Decimal(7) | |
588 | Decimal("0.142857142857142857142857142857142857") | |
589 | </pre></div> | |
590 | ||
591 | <P> | |
592 | ||
593 | <DIV CLASS="navigation"> | |
594 | <div class='online-navigation'> | |
595 | <p></p><hr /> | |
596 | <table align="center" width="100%" cellpadding="0" cellspacing="2"> | |
597 | <tr> | |
598 | <td class='online-navigation'><a rel="prev" title="10. Brief Tour of" | |
599 | href="node12.html"><img src='../icons/previous.png' | |
600 | border='0' height='32' alt='Previous Page' width='32' /></A></td> | |
601 | <td class='online-navigation'><a rel="parent" title="Python Tutorial" | |
602 | href="tut.html"><img src='../icons/up.png' | |
603 | border='0' height='32' alt='Up One Level' width='32' /></A></td> | |
604 | <td class='online-navigation'><a rel="next" title="12. What Now?" | |
605 | href="node14.html"><img src='../icons/next.png' | |
606 | border='0' height='32' alt='Next Page' width='32' /></A></td> | |
607 | <td align="center" width="100%">Python Tutorial</td> | |
608 | <td class='online-navigation'><a rel="contents" title="Table of Contents" | |
609 | href="node2.html"><img src='../icons/contents.png' | |
610 | border='0' height='32' alt='Contents' width='32' /></A></td> | |
611 | <td class='online-navigation'><img src='../icons/blank.png' | |
612 | border='0' height='32' alt='' width='32' /></td> | |
613 | <td class='online-navigation'><a rel="index" title="Index" | |
614 | href="node19.html"><img src='../icons/index.png' | |
615 | border='0' height='32' alt='Index' width='32' /></A></td> | |
616 | </tr></table> | |
617 | <div class='online-navigation'> | |
618 | <b class="navlabel">Previous:</b> | |
619 | <a class="sectref" rel="prev" href="node12.html">10. Brief Tour of</A> | |
620 | <b class="navlabel">Up:</b> | |
621 | <a class="sectref" rel="parent" href="tut.html">Python Tutorial</A> | |
622 | <b class="navlabel">Next:</b> | |
623 | <a class="sectref" rel="next" href="node14.html">12. What Now?</A> | |
624 | </div> | |
625 | </div> | |
626 | <hr /> | |
627 | <span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span> | |
628 | </DIV> | |
629 | <!--End of Navigation Panel--> | |
630 | <ADDRESS> | |
631 | See <i><a href="about.html">About this document...</a></i> for information on suggesting changes. | |
632 | </ADDRESS> | |
633 | </BODY> | |
634 | </HTML> |