This second tour covers more advanced modules that support professional programming needs. These modules rarely occur in small scripts.
11.1. Output Formatting
reprlib, provides a version ofrepr()customized for abbreviated displays of large or deeply nested containers1
2
3import reprlib
reprlib.repr(set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"pprint, offers more sophisticated control over printing both built-in and user defined objects in a way that is readable by the interpreter. (auto newline and indentation)1
2
3pprint.pprint(sys.path)
# vs
print(sys.path)textwrap, formats paragraphs of text to fit a given screen width.1
2
3import textwrap
longstring = 'Hello'*100
print(textwrap.fill(longstring , width = 5))locale, accesses a database of culture specific data formats, this will be useful when you do international coding(lol)
11.2. Templating
string.Templateall you to use template strings.
1 | from string import Template |
Template subclasses can specify a custom delimiter
1
2
3
4
5
6
7
8
9
10
11from string import Template as T
class myt(T):
delimiter = '%' # change the delimiter
t = myt('%origin ---> %new')
d = {'old':'new' , 'small' : 'big' }
for k,v in d.items():
print(t.safe_substitute(origin = k,new = v))
old ---> new
small ---> bigstring template makes it possible to substitute custom templates for XML files, plain text reports, and HTML web reports.
11.3. Working with Binary Data Record Layouts
The
structmodule providespack()andunpack()functions for working with variable length binary record formats.
11.4. Multi-threading
Threading is a technique for decoupling tasks which are not sequentially dependent.
It can run something in the background while accepting user input.
- the preferred approach to task coordination is to concentrate all access to a resource in a single thread and then use the
queuemodule to feed that thread with requests from other threads.
11.5. Logging
The
loggingmodule offers a full featured and flexible logging system. At its simplest, log messages are sent to a file or tosys.stderr
1 | import logging |
1 | WARNING:root:Warning:config file server.conf not found |
11.6. Weak References
Python does automatic memory management (reference counting for most objects and garbage collection to eliminate cycles). The memory is freed shortly after the last reference to it has been eliminated.
The
weakrefmodule provides tools for tracking objects without creating a reference.
1 | import weakref, gc |
11.7. Tools for Working with Lists
The
arraymodule provides anarray()object that is like a list that stores only homogeneous data and stores it more compactly.1
2
3
4
5
6from array import array
a = array('H', [4000, 10, 700, 22222])
sum(a)
26932
a[1:3]
array('H', [10, 700])The
collectionsmodule provides adeque()objectThe
heapqmodule provides functions for implementing heaps based on regular lists.
11.8. Decimal Floating Point Arithmetic
The
decimalmodule offers aDecimaldatatype for decimal floating point arithmetic.Compared to the built-in
floatimplementation of binary floating point, the class is especially helpful for
- financial applications and other uses which require exact decimal representation,
- control over precision,
- control over rounding to meet legal or regulatory requirements,
- tracking of significant decimal places, or
- applications where the user expects the results to match calculations done by hand.
1 | sum([Decimal('0.1')]*10) == Decimal('1.0') |
1 | from decimal import * |
1 | getcontext().prec = 36 |