python / python/mypy

Non-empty container types

未关闭
#9,745 18 条评论 54 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

feature
主要语言
Python
星标
20.6k
派生
3.3k
PR 合并指标
PR 指标待抓取

描述

Feature

It would be very helpful to have a way of specifying that a container type must be non-empty.

Pitch

As an example of why this feature would be helpful, consider the following function, average:

from typing import List


def average(numbers: List[float]) -> float:
    """Return the average of a non-empty list of numbers."""
    return sum(numbers) / len(numbers)

Rather than relying on exceptions for handling the case when the number of numbers is zero, is seems like something along the lines of the following would be more convenient and more explicit:

from typing import List, NonEmpty


def average(numbers: NonEmpty[List[float]]) -> float:
    """Return the average of a non-empty list of numbers."""
    return sum(numbers) / len(numbers)

I don't know anything about the way mypy is implemented so I'm not sure if this is a possible.

贡献指南

打开贡献指南

从这里开始

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

调研方向

该 issue 提议为 Python 容器注解引入 NonEmpty 类型,并以 NonEmpty[List[float]] 和 average 函数作为示例。首先检查 mypy 现有的类型系统和 typing 构造支持;该 issue 没有指定文件或测试。完成这项工作需要达成一致的设计,并实现能够保持容器非空不变量的类型检查。

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

评估

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

把新 issue 发到你的邮箱

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