使用 Python 3.7 功能切片无限生成器

了解更多关于此功能和另外两个未充分利用但仍然有用的 Python 功能。
32 位读者喜欢这篇文章。
Hands on a keyboard with a Python book

WOCinTech Chat。由 Opensource.com 修改。CC BY-SA 4.0

这是关于 Python 3.x 版本中首次出现的功能系列文章中的第八篇。Python 3.7 于 2018 年首次发布,即使它已经发布几年了,但它引入的许多功能仍未被充分利用且非常酷。以下是其中三个。

延迟评估注解

在 Python 3.7 中,只要激活正确的 __future__ 标志,注解就不会在运行时评估

from __future__ import annotations

def another_brick(wall: List[Brick], brick: Brick) -> Education:
    pass
another_brick.__annotations__
    {'wall': 'List[Brick]', 'brick': 'Brick', 'return': 'Education'}

这允许递归类型(引用自身的类)和其他有趣的事情。但是,这意味着如果您想进行自己的类型分析,则需要显式使用 ast

import ast
raw_type = another_brick.__annotations__['wall']
[parsed_type] = ast.parse(raw_type).body
subscript = parsed_type.value
f"{subscript.value.id}[{subscript.slice.id}]"
    'List[Brick]'

itertools.islice 支持 __index__

Python 中的序列切片长期以来接受各种类整数对象(具有 __index__() 的对象)作为有效的切片部分。但是,直到 Python 3.7,itertools.islice(核心 Python 中切片无限生成器的唯一方法)才获得此支持。

例如,现在可以使用 numpy.short 大小的整数来切片无限生成器

import numpy
short_1 = numpy.short(1)
short_3 = numpy.short(3)
short_1, type(short_1)
    (1, numpy.int16)
import itertools
list(itertools.islice(itertools.count(), short_1, short_3))
    [1, 2]

functools.singledispatch() 注解注册

如果您认为 singledispatch 不可能更酷了,那您就错了。现在可以基于注解进行注册了

import attr
import math
from functools import singledispatch

@attr.s(auto_attribs=True, frozen=True)
class Circle:
    radius: float
        
@attr.s(auto_attribs=True, frozen=True)
class Square:
    side: float

@singledispatch
def get_area(shape):
    raise NotImplementedError("cannot calculate area for unknown shape",
                              shape)

@get_area.register
def _get_area_square(shape: Square):
    return shape.side ** 2

@get_area.register
def _get_area_circle(shape: Circle):
    return math.pi * (shape.radius ** 2)

get_area(Circle(1)), get_area(Square(1))
    (3.141592653589793, 1)

欢迎来到 2017 年

Python 3.7 大约在四年前发布,但此版本中首次出现的一些功能很酷且未被充分利用。如果您还没有这样做,请将它们添加到您的工具包中。

接下来阅读什么
标签
Moshe sitting down, head slightly to the side. His t-shirt has Guardians of the Galaxy silhoutes against a background of sound visualization bars.
自 1998 年以来,Moshe 一直参与 Linux 社区,在 Linux “安装聚会” 中提供帮助。自 1999 年以来,他一直在编写 Python 程序,并为核心 Python 解释器做出了贡献。Moshe 在这些术语出现之前就已经是 DevOps/SRE,他非常关心软件可靠性、构建可重现性以及其他此类事情。

评论已关闭。

© . All rights reserved.