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

开发 后端
了解更多关于这个和其他两个未被充分利用但仍然有用的 Python 特性。这是关于 Python 3.x 首发特性系列文章的第八篇。Python 3.7 于 2018 年首次发布,尽管它已经发布了几年,但它引入的许多特性都未被充分利用,而且相当酷。下面是其中的三个。

了解更多关于这个和其他两个未被充分利用但仍然有用的 Python 特性。

这是关于 Python 3.x 首发特性系列文章的第八篇。Python 3.7 于 2018 年首次发布,尽管它已经发布了几年,但它引入的许多特性都未被充分利用,而且相当酷。下面是其中的三个。

注解推迟评估

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

  1. from __future__ import annotations
  2.  
  3. def another_brick(wall: List[Brick], brick: Brick) -> Education:
  4. pass
  1. another_brick.__annotations__
  1. {'wall': 'List[Brick]', 'brick': 'Brick', 'return': 'Education'}

它使递归类型(指向自己的类)和其他有趣的事情成为了可能。然而,这意味着如果你想做自己的类型分析,你需要明确地使用 ast

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

itertools.islice 支持 index

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

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

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

functools.singledispatch() 注解注册

如果你认为 singledispatch 已经很酷了,你错了。现在可以根据注解来注册了:

  1. import attr
  2. import math
  3. from functools import singledispatch
  4.  
  5. @attr.s(auto_attribs=True, frozen=True)
  6. class Circle:
  7.     radius: float
  8.        
  9. @attr.s(auto_attribs=True, frozen=True)
  10. class Square:
  11.     side: float
  12.  
  13. @singledispatch
  14. def get_area(shape):
  15.     raise NotImplementedError("cannot calculate area for unknown shape",
  16.                               shape)
  17.  
  18. @get_area.register
  19. def _get_area_square(shape: Square):
  20.     return shape.side ** 2
  21.  
  22. @get_area.register
  23. def _get_area_circle(shape: Circle):
  24.     return math.pi * (shape.radius ** 2)
  25.  
  26. get_area(Circle(1)), get_area(Square(1))
  1.     (3.141592653589793, 1)

欢迎来到 2017 年

Python 3.7 大约是四年前发布的,但是在这个版本中首次出现的一些特性非常酷,而且没有得到充分利用。如果你还没使用,那么将它们添加到你的工具箱中。 

 

责任编辑:庞桂玉 来源: Linux中国
相关推荐

2017-09-06 09:26:03

Python生成器协程

2023-07-21 17:08:30

2021-12-04 22:07:44

Python

2020-04-30 21:40:14

C#特性编程语言

2022-10-27 13:58:32

Python编程生成器

2011-12-23 13:42:05

JavaScript

2021-04-22 21:15:38

Generator函数生成器

2010-09-07 16:31:17

SQL语句insert

2015-08-25 11:07:58

2017-07-01 16:02:39

分布式ID生成器

2020-10-05 21:57:43

Python生成器可迭代对象

2022-10-17 18:29:55

2017-06-26 16:26:15

Python迭代对象迭代器

2021-08-23 07:32:57

生成器开发代码

2023-05-04 16:24:10

人工智能图像生成器

2023-02-07 16:11:41

2022-07-25 10:27:36

背景生成器工具前端

2023-11-15 13:35:00

迭代器生成器Python

2010-03-26 13:03:23

Boost.Pytho

2010-07-20 13:56:26

Python迭代器生成器
点赞
收藏

51CTO技术栈公众号