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