Python3.8的新增特性( 二 )


>>> user = 'eric_idle'>>> member_since = date(1975, 7, 31)>>> f'{user=} {member_since=}'"user='eric_idle' member_since=datetime.date(1975, 7, 31)"通常的 f-字符串格式说明符允许更细致地控制所要显示的表达式结果:
>>> delta = date.today() - member_since>>> f'{user=!s}{delta.days=:,d}''user=eric_idledelta.days=16,075'= 说明符将输出整个表达式,以便详细演示计算过程:
>>> print(f'{theta=}{cos(radians(theta))=:.3f}')theta=30cos(radians(theta))=0.866新增模块新增的 importlib.metadata 模块提供了从第三方包读取元数据的(临时)支持 。例如,它可以提取一个已安装软件包的版本号、入口点列表等等:
>>> from importlib.metadata import version, requires, files>>> version('requests')'2.22.0'>>> list(requires('requests'))['chardet (<3.1.0,>=3.0.2)']>>> list(files('requests'))[:5][PackagePath('requests-2.22.0.dist-info/INSTALLER'), PackagePath('requests-2.22.0.dist-info/LICENSE'), PackagePath('requests-2.22.0.dist-info/METADATA'), PackagePath('requests-2.22.0.dist-info/RECORD'), PackagePath('requests-2.22.0.dist-info/WHEEL')]这个在进行函数式编程的时候会用到,一般情况下使用比较少
改进的部分模块

  • asyncio
asyncio.run() 已经从暂定状态晋级为稳定 API 。此函数可被用于执行一个 coroutine 并返回结果,同时自动管理事件循环
import asyncioasync def main():await asyncio.sleep(0)return 42asyncio.run(main())这大致等价于:
import asyncioasync def main():await asyncio.sleep(0)return 42loop = asyncio.new_event_loop()asyncio.set_event_loop(loop)try:loop.run_until_complete(main())finally:asyncio.set_event_loop(None)loop.close()精简了非常多的代码,现在可以作为首推方式使用
  • collections
collections.namedtuple() 的 _asdict() 方法现在将返回dict而不是 collections.OrderedDict 。OrderedDict为有序字典,目前普通字典已经保证具有确定的元素顺序 。如果还需要 OrderedDict 的额外特性,建议的解决方案是将结果转换为需要的类型: OrderedDict(nt._asdict()) 。
  • cProfile
cProfile.Profile 类现在可被用作上下文管理器 。在运行时对一个代码块实现性能分析:
import cProfilewith cProfile.Profile() as profiler:# code to be profiled...还有functools、inspect、itertools、operator等模块,我们后面单独介绍,这些都是Python中非常方便的模块 。




推荐阅读