python / python/typing

Feature Request: Type hint for Fixed Length Homogeneous Sequences

未关闭
#786 7 条评论 47 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

topic: feature
主要语言
Python
星标
1.8k
派生
302
平均合并
23 小时
30 天内合并 PR
8

描述

Feature

A concise way to hint that a sequence of homogenous types is a set length. i.e The items in the sequence are all of the same type, the sequence is iterable, and cannot grow larger or smaller.

Pitch

Currently, the recommended way to add type hints to fixed-length sequences is to use Tuples 1. i.e

def foo(ten_floats: Tuple[float,float,float,float,float,float,float,float,float,float]):
    ...

For longer lists, this repetition is tedious and prone to error.
It would be nice to have a shorthand for defining homogeneous tuples. e.g

def foo(ten_floats: HomogeneousTuple[float, 10]):
    ...

Although the name Tuple does not signal intent very well. The real thing that we are trying to signal is that this is a sequence of floats of length 10. It does not necessarily have to be a Tuple, it just has to be iterable, and have 10 items, that cannot grow larger or smaller. If I wanted to pass the function a List, this should also pass static type checkers, as long as it has 10 floats.

Possible Implementation

I am not a core python developer, I have never even looked at the implementation of the typing module, and I'm not even that good of a python developer, so please forgive me if this is nonsense.

In Python 3.10 or newer [2] we will be able to use the unpack operator in subscript. So we might be able to do something like:

_t=[float]*10
def foo(ten_floats: Tuple[*_t]):
    ...

Using TypeVars, we could generalize this function to accept 10 of any type (as long as they are all the same type)

T=TypeVar('T')
TenTypeVars=[T]*10
def foo(ten_homogeneous_items: Tuple[*TenTypeVars]):
    ...

Following this logic, perhaps a generic type hint for Fixed Length Homogeneous Sequences could be implemented with

class FixedLengthHomogeneousSequence(Generic[T, N], Tuple[*[T]*N]):
    ...

FixedLengthHomogeneousSequence is a bit wordy. So perhaps FixedList would be a better name.

[2] (I think this is true). Pylance gave me an error saying this was the case. I think it's related to https://www.python.org/dev/peps/pep-0622/

贡献指南

这个仓库没有索引到贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

该 issue 未指出实现文件、测试或入口点。首先查看 typing 模块现有的 Tuple、TypeVar 和泛型序列行为,然后将提议的语法与所引用的 PEP 进行比较;完成的条件是确定一套达成共识的类型检查设计、实现位置,以及覆盖定长同质序列的测试。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
tooling
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
需要澄清
新手友好度
20/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。