这是关于 Python 3.x 版本中首次出现的功能系列文章中的第十篇。其中一些版本已经发布一段时间了。Python 3.9 于 2020 年首次发布,其中包含很酷的新功能,但仍未得到充分利用。以下是其中三个。
添加字典
假设您有一个带有“默认值”的字典,并且您想使用参数更新它。在 Python 3.9 之前,最好的选择是复制默认字典,然后使用 .update()
方法。
Python 3.9 为字典引入了联合运算符
defaults = dict(who="someone", where="somewhere")
params = dict(where="our town", when="today")
defaults | params
{'who': 'someone', 'where': 'our town', 'when': 'today'}
请注意,顺序很重要。在这种情况下,params
中的 where
值会覆盖默认值,这是应该的。
删除前缀
如果您使用 Python 完成过临时文本解析或清理,您将编写过类似这样的代码
def process_pricing_line(line):
if line.startswith("pricing:"):
return line[len("pricing:"):]
return line
process_pricing_line("pricing:20")
'20'
这种代码容易出错。例如,如果字符串被错误地复制到下一行,价格将变为 0
而不是 20
,并且它会悄无声息地发生。
自 Python 3.9 以来,字符串具有 .removeprefix()
方法
>>> "pricing:20".removeprefix("pricing:")
'20'
任意装饰器表达式
以前,关于装饰器中允许哪些表达式的规则记录不足且难以理解。例如,虽然
@item.thing
def foo():
pass
是有效的,并且
@item.thing()
def foo():
pass
是有效的,但类似的
@item().thing
def foo():
pass
会产生语法错误。
从 Python 3.9 开始,任何表达式都可作为装饰器使用
from unittest import mock
item = mock.MagicMock()
@item().thing
def foo():
pass
print(item.return_value.thing.call_args[0][0])
<function foo at 0x7f3733897040>
虽然在装饰器行中保持简单的表达式仍然是一个好主意,但这现在是一个人为的决定,而不是 Python 解析器的选择。
欢迎来到 2020 年
Python 3.9 大约在一年前发布,但在此版本中首次出现的一些功能很酷且未被充分利用。如果您还没有使用它们,请将它们添加到您的工具包中。
评论已关闭。