Python 3.9的新变化

新版本预计仅在十月发布,但是您已经可以阅读其中的内容并测试初步版本。
在我看来,最有趣的是更改。

首先,我们提醒我们,正在逐渐删除支持与2.7版向后兼容的图层,并要求他们注意DeprecationWarning并消除它们。一些警告仍将保持在3.9,但最好删除它们。

词典
合并运算符(PEP-584到现在为止,有几种合并词典的方法,但是每种方法都有微小的缺陷或细微差别。
组合字典的几种方法
1. update
d1 = {'one': 1}
d2 = {'two': 2}
#     ,..
d1.update(d2)
# ...  . 
united_dict = d1.copy()
united_dict.update(d2)

2.
united_dict = {**d1, **d2}

, , , .
3. dict(d1, **d2), . , d2 .
4. collections.ChainMap
.
, , .
from collections import ChainMap
d1 = {'one': 1}
d2 = {'two': 2}
united_dict = ChainMap(d1, d2)

, , , . , - .

现在您可以简单地编写
united_dict = d1 | d2
# ,        ,    update():
d1 |= d2

因此,我认为将字典与一个运算符组合在一起的新可能性将吸引许多人。

容器和其他可以参数化的类型的注释的简化(PEP-0585
以下创新对使用类型注释的人员非常有用。
现在简化了集合的注释,例如列表和字典,以及通常参数化的类型。

对于这些类型,引入了泛型一词-这是可以参数化的类型,通常是容器。例如,dict。问题是如何正确翻译它,以免打断牙齿。我真的不想使用“泛型”一词。因此,在评论中,我真的很期待其他建议。也许在翻译的某个地方有个更好的名字?
参数化的泛型:dict [str,int]。

因此,对于此类类型,您现在无需从键入中导入相应的注释,而只需使用类型名称即可。
例如
# 
from typing import List
List[str]
# 
list[int]

.

:
# 
from typing import OrderedDict
OrderedDict[str, int]
# 
from collections import OrderedDict
OrderedDict[str, int]

tuple # typing.Tuple
list # typing.List
dict # typing.Dict
set # typing.Set
frozenset # typing.FrozenSet
type # typing.Type
collections.deque
collections.defaultdict
collections.OrderedDict
collections.Counter
collections.ChainMap
collections.abc.Awaitable
collections.abc.Coroutine
collections.abc.AsyncIterable
collections.abc.AsyncIterator
collections.abc.AsyncGenerator
collections.abc.Iterable
collections.abc.Iterator
collections.abc.Generator
collections.abc.Reversible
collections.abc.Container
collections.abc.Collection
collections.abc.Callable
collections.abc.Set # typing.AbstractSet
collections.abc.MutableSet
collections.abc.Mapping
collections.abc.MutableMapping
collections.abc.Sequence
collections.abc.MutableSequence
collections.abc.ByteString
collections.abc.MappingView
collections.abc.KeysView
collections.abc.ItemsView
collections.abc.ValuesView
contextlib.AbstractContextManager # typing.ContextManager
contextlib.AbstractAsyncContextManager # typing.AsyncContextManager
re.Pattern # typing.Pattern, typing.re.Pattern
re.Match # typing.Match, typing.re.Match


对于字符串,出现了removeprefix()和removesuffix()(PEP 616方法,
这里的一切都很简单。如果该行以前缀开头,则将返回不带该前缀的行。如果前缀重复多次,则只会被删除一次。后缀类似:
some_str = 'prefix of some string and here suffix'
some_str.removeprefix('prefix')
>> ' of some string and here suffix'
some_str.removesuffix('suffix')
>> 'prefix of some string and here '

当前替代品
1. , , — removeprefix.
def removeprefix(self: str, prefix: str, /) -> str:
    if self.startswith(prefix):
        return self[len(prefix):]
    else:
        return self[:]

2. lstrip, rstrip:
	'foobar'.lstrip(('foo',))

, , .

数学模块中
一些更改现在,用于查找最大公约数math.gcd()函数接受一个整数列表,因此您可以找到一个包含两个以上数字的公约数。
有一个用于确定math.lcm()最小公倍数的函数,该函数还接受无限数量的整数。
以下两个功能是相互联系的。
math.nextafter(x,y) -如果沿y方向移动,则计算最接近x的浮点数。
math.ulp(x)-代表“最后一个单位”,取决于计算机计算的准确性。对于正数,将返回该数字的最小值,这样,当将其加x + ulp(x)时,将获得最接近的浮点数。
import math

math.gcd(24, 36)
>> 12
math.lcm(12, 18)
>> 36
math.nextafter(3, -1)
>> 2.9999999999999996
3 - math.ulp(3)
>> 2.9999999999999996
math.nextafter(3, -1) + math.ulp(3)
>> 3.0 

现在,任何有效的表达式都可以成为修饰符(PEP-0614
从修饰符中删除了限制,根据该限制,只有名称可以充当修饰符,并且其语法仅允许使用点分隔。

我认为没有很多人考虑过这种限制的存在,但是pep的描述举例说明了一项创新使代码更加一致。打个比方,我们可以引用
简化和人为的示例:
def a(func):
	def wrapper():
		print('a')
		func()
	return wrapper
	
def b(func):
	def wrapper():
		print('b')
		func()
	return wrapper
	
decorators = [a, b]

@decorators[0] #   3.8        
def some_func():
	print('original')
	
some_func()
>> a
>> original

未分析方法(bpo-38870)被添加到ast模块中
,顾名思义,它可以使用ast.AST对象编译源字符串。曾经,我什至要使用此方法,令人惊讶的是没有这种方法。
例:
import ast
parsed = ast.parse('import pprint; pprint.pprint({"one":1, "two":2})')
unparsed_str = ast.unparse(parsed)
print(unparsed_str)
>> import pprint
>> pprint.pprint({'one': 1, 'two': 2})
exec(unparsed_str)
>> {'one': 1, 'two': 2}

用于对有向无环图进行拓扑排序的新functools.TopologicalSorter类(bpo-17005
传递给排序器的图应该是一个字典,其中键是图的顶点,并且值是一个带有前任的可迭代对象(弧的弧指向键的顶点)。通常,任何散列类型都适合作为键。
例:
:

from functools import TopologicalSorter
graph = graph = {8: [3, 7], 11: [5, 7], 2: [11], 9: [8, 11], 10: [3, 11]}
t_sorter = TopologicalSorter(graph)
t_sorted_list = list(t_sorted_list.static_order()) #  ,    ,     static_order.
>> [3, 7, 5, 8, 11, 2, 9, 10]


, TopologicalSorter add. , , .

我们等待已久的新状态
添加到http.HTTPStatus 103 EARLY_HINTS
418 IM_A_TEAPOT
425 TOO_EARLY

还有一些其他更改:
  • 内置类型(范围,元组,集合,frozenset,列表)被加速(PEP-590
  • 现在,“” .replace(“”,s,n)对于所有非零n返回s,而不是空字符串。对于字节和字节数组都是如此。
  • ipaddress现在支持解析带有目标的IPv6地址。

由于3.9版仍在开发中,可能还会添加更多更改,因此我计划在必要时补充本文。

您可以阅读更多详细信息:
docs.python.org/3.9/whatsnew/3.9.html
www.python.org/downloads/release/python-390a6
通常,并不是说未来的变化是每个人都在等待很长时间的事情,没有尽管有一些不错的观点,但无法实现。您觉得新版本中最有趣的是什么?

UPD:
已更新到最新版本的链接;
添加了有关类型注释的PEP-0585

All Articles