11. 标准类库之旅——第二部分

第二次访问涵盖了更高级的模块,支持专业编程需求。这些模块很少出现在小脚本中。

11.1. 输出格式化

这个 reprlib 模块提供的版本 repr() 为大型或深嵌套容器的缩写显示定制:

>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"

这个 pprint 模块以解释器可读的方式对打印内置和用户定义的对象提供更复杂的控制。当结果超过一行时,“漂亮的打印机”会添加换行符和缩进,以便更清晰地显示数据结构:

>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
...     'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
[[[['black', 'cyan'],
   'white',
   ['green', 'red']],
  [['magenta', 'yellow'],
   'blue']]]

这个 textwrap 模块设置文本段落的格式以适应给定的屏幕宽度:

>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print(textwrap.fill(doc, width=40))
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.

这个 locale 模块访问区域性特定数据格式的数据库。locale的format函数的grouping属性提供了使用组分隔符直接格式化数字的方法:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = locale.localeconv()          # get a mapping of conventions
>>> x = 1234567.8
>>> locale.format("%d", x, grouping=True)
'1,234,567'
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
...                      conv['frac_digits'], x), grouping=True)
'$1,234,567.80'

11.2. 模板法

这个 string 模块包括多功能 Template 使用适合最终用户编辑的简化语法初始化。这允许用户自定义其应用程序,而不必更改应用程序。

格式使用的占位符名称由 $ 使用有效的python标识符(字母数字字符和下划线)。用大括号将占位符括起来,可以让它后面跟着更多的字母数字字母,并且没有中间的空格。写作 $$ 创建单个转义 $ ::

>>> from string import Template
>>> t = Template('${village}folk send $$10 to $cause.')
>>> t.substitute(village='Nottingham', cause='the ditch fund')
'Nottinghamfolk send $10 to the ditch fund.'

这个 substitute() 方法提出 KeyError 当字典或关键字参数中未提供占位符时。对于邮件合并样式的应用程序,用户提供的数据可能不完整,并且 safe_substitute() 方法可能更合适---如果缺少数据,将保持占位符不变::

>>> t = Template('Return the $item to $owner.')
>>> d = dict(item='unladen swallow')
>>> t.substitute(d)
Traceback (most recent call last):
  ...
KeyError: 'owner'
>>> t.safe_substitute(d)
'Return the unladen swallow to $owner.'

模板子类可以指定自定义分隔符。例如,照片浏览器的批量重命名实用程序可以选择对占位符使用百分号,如当前日期、图像序列号或文件格式:

>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):
...     delimiter = '%'
>>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format):  ')
Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f

>>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')
>>> for i, filename in enumerate(photofiles):
...     base, ext = os.path.splitext(filename)
...     newname = t.substitute(d=date, n=i, f=ext)
...     print('{0} --> {1}'.format(filename, newname))

img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg

另一个用于模板化的应用程序是将程序逻辑与多个输出格式的细节分离开来。这使得用自定义模板替换XML文件、纯文本报告和HTML Web报告成为可能。

11.3. 使用二进制数据记录布局

这个 struct 模块提供 pack()unpack() 用于处理可变长度二进制记录格式的函数。下面的示例演示如何在不使用 zipfile 模块。封装代码 "H""I" 分别表示两个和四个字节的无符号数。这个 "<" 指示它们是标准大小,以小尾数字节顺序:

import struct

with open('myfile.zip', 'rb') as f:
    data = f.read()

start = 0
for i in range(3):                      # show the first 3 file headers
    start += 14
    fields = struct.unpack('<IIIHH', data[start:start+16])
    crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

    start += 16
    filename = data[start:start+filenamesize]
    start += filenamesize
    extra = data[start:start+extra_size]
    print(filename, hex(crc32), comp_size, uncomp_size)

    start += extra_size + comp_size     # skip to the next header

11.4. 多线程

线程是一种分离不依赖于顺序的任务的技术。线程可以用来提高接受用户输入的应用程序的响应能力,而其他任务则在后台运行。一个相关的用例正在与另一个线程中的计算并行地运行I/O。

下面的代码显示高级 threading 当主程序继续运行时,模块可以在后台运行任务:

import threading, zipfile

class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)
        self.infile = infile
        self.outfile = outfile

    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
        f.write(self.infile)
        f.close()
        print('Finished background zip of:', self.infile)

background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')

background.join()    # Wait for the background task to finish
print('Main program waited until background was done.')

多线程应用程序的主要挑战是协调共享数据或其他资源的线程。为此,线程模块提供了许多同步原语,包括锁、事件、条件变量和信号量。

虽然这些工具功能强大,但微小的设计错误可能导致难以重现的问题。因此,任务协调的首选方法是将对资源的所有访问集中在一个线程中,然后使用 queue 模块向该线程提供来自其他线程的请求。应用程序使用 Queue 用于线程间通信和协调的对象更易于设计、更可读和更可靠。

11.5. 登录

这个 logging 模块提供全功能和灵活的日志记录系统。最简单的是,日志消息被发送到文件或 sys.stderr ::

import logging
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down')

这将产生以下输出:

WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down

默认情况下,信息和调试消息将被抑制,并将输出发送到标准错误。其他输出选项包括通过电子邮件、数据报、套接字或HTTP服务器路由消息。新过滤器可以根据邮件优先级选择不同的路由: DEBUGINFOWARNINGERRORCRITICAL .

日志记录系统可以直接从python配置,也可以从用户可编辑的配置文件加载,以便在不改变应用程序的情况下自定义日志记录。

11.6. 弱引用

python执行自动内存管理(对大多数对象和 garbage collection 消除循环)。内存在最后一次引用被清除后不久被释放。

这种方法对大多数应用程序都很好,但有时只需要跟踪被其他对象使用的对象。不幸的是,跟踪它们会创建一个引用,使它们成为永久的。这个 weakref 模块提供跟踪对象而不创建引用的工具。当不再需要该对象时,它将自动从weakref表中删除,并为weakref对象触发回调。典型的应用程序包括缓存创建成本高昂的对象:

>>> import weakref, gc
>>> class A:
...     def __init__(self, value):
...         self.value = value
...     def __repr__(self):
...         return str(self.value)
...
>>> a = A(10)                   # create a reference
>>> d = weakref.WeakValueDictionary()
>>> d['primary'] = a            # does not create a reference
>>> d['primary']                # fetch the object if it is still alive
10
>>> del a                       # remove the one reference
>>> gc.collect()                # run garbage collection right away
0
>>> d['primary']                # entry was automatically removed
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    d['primary']                # entry was automatically removed
  File "C:/python310/lib/weakref.py", line 46, in __getitem__
    o = self.data[key]()
KeyError: 'primary'

11.7. 使用列表的工具

内置列表类型可以满足许多数据结构需求。但是,有时需要具有不同性能权衡的替代实现。

这个 array 模块提供 array() 对象,类似于只存储同构数据并更紧凑地存储数据的列表。以下示例显示了一个存储为双字节无符号二进制数(类型代码)的数字数组 "H" )对于python int对象的常规列表,而不是通常的每个条目16个字节:

>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])

这个 collections 模块提供 deque() 对象,该对象类似于一个列表,在左侧具有更快的附加和弹出,但在中间查找较慢。这些对象非常适合实现队列和宽度优先树搜索:

>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print("Handling", d.popleft())
Handling task1
unsearched = deque([starting_node])
def breadth_first_search(unsearched):
    node = unsearched.popleft()
    for m in gen_moves(node):
        if is_goal(m):
            return m
        unsearched.append(m)

除了替代列表实现之外,库还提供其他工具,如 bisect 具有操作排序列表功能的模块:

>>> import bisect
>>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
>>> bisect.insort(scores, (300, 'ruby'))
>>> scores
[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]

这个 heapq 模块提供基于常规列表实现堆的功能。最低值项始终保持在零位置。这对于重复访问最小元素但不想运行完整列表排序的应用程序很有用:

>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data)                      # rearrange the list into heap order
>>> heappush(data, -5)                 # add a new entry
>>> [heappop(data) for i in range(3)]  # fetch the three smallest entries
[-5, 0, 1]

11.8. 十进制浮点运算

这个 decimal 模块提供 Decimal 十进制浮点运算的数据类型。与内置 float 实现二进制浮点,类尤其有助于

  • 需要精确小数表示的财务应用和其他用途,

  • 控制精度,

  • 控制舍入以满足法律或法规要求;

  • 有效小数点的跟踪,或

  • 用户期望结果与手工计算匹配的应用程序。

例如,对70%的调用费计算5%的税会得到不同的十进制浮点和二进制浮点结果。如果结果四舍五入到最接近的分值,则差异将变得显著:

>>> from decimal import *
>>> round(Decimal('0.70') * Decimal('1.05'), 2)
Decimal('0.74')
>>> round(.70 * 1.05, 2)
0.73

这个 Decimal 结果保持尾随零,自动从具有两个位置重要性的被乘数推断四个位置重要性。小数复制了手工完成的数学,避免了二进制浮点不能精确表示小数量时可能出现的问题。

精确表示使 Decimal 类以执行不适用于二进制浮点的模块计算和相等性测试:

>>> Decimal('1.00') % Decimal('.10')
Decimal('0.00')
>>> 1.00 % 0.10
0.09999999999999995

>>> sum([Decimal('0.1')]*10) == Decimal('1.0')
True
>>> sum([0.1]*10) == 1.0
False

这个 decimal 模块提供所需精度的算术:

>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857')