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模块访问文化特定数据格式的数据库。语言环境格式Function的分组属性提供了一种使用组分隔符格式化数字的直接方法:

>>> 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. Templating

string模块包括通用的Template类,该类具有简化的语法,适合finally用户编辑。这使用户可以自定义其应用程序,而不必更改应用程序。

该格式使用由$组成的占位符名称,并带有有效的 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.'

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

>>> 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模块的情况下循环浏览 ZIP 文件中的头信息。组装代码"H""I"分别表示两个和四个字节的无符号数字。 "<"表示它们是标准大小,并且以小尾数字节 Sequences 排列:

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. Multi-threading

线程是一种用于解耦与 Sequences 无关的任务的技术。线程可用于提高在后台运行其他任务时接受用户 Importing 的应用程序的响应能力。一个相关的用例是与另一个线程中的计算并行运行 I/O。

以下代码显示了高级threading模块如何在主程序 continue 运行的同时在后台运行任务:

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.')

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

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

11.5. Logging

logging模块提供了Function齐全且灵活的日志记录系统。简单来说,日志消息将发送到文件或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

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

可以直接从 Python 配置日志记录系统,也可以从用户可编辑的配置文件中加载日志记录系统以进行自定义日志记录,而无需更改应用程序。

11.6. 参考文献薄弱

Python 执行自动内存 Management(大多数对象的引用计数和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:/python38/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模块,该模块具有用于处理已排序列表的Function:

>>> 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模块提供用于基于常规列表实现堆的Function。最低值的条目始终保持在零位置。这对于重复访问最小元素但不想运行完整列表排序的应用程序很有用:

>>> 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结果保持尾随零,自动从具有两个位置有效位的被乘数中推断出四个位置重要度。十进制再现手工完成的 math 运算,避免了当二进制浮点不能精确表示十进制数量时可能出现的问题。

精确的表示形式使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')