用这个 Python 3.7 的特性来切片无限生成器

发表于:2021-6-15 09:21

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Moshe Zadka    来源:Linux中国

  注解推迟评估
  在 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 中的序列切片长期以来一直接受各种 类 int 对象(具有 __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)

  本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号