python / python/typing

Generic versions of enum.Enum?

未关闭
#535 15 条评论 65 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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

描述

(First of all, apologies if this is not the proper place for suggesting this, or if this has already been discussed, I couldn't find anything related to this so I opened an issue here.)

So I've recently come across a situation like this:
I've defined an enum

from enum import Enum

class MyEnum(Enum):
    a = 1
    b = 2
    c = 3

and need to use the value of an enum member later on:

some_func(MyEnum.a.value)

Analyzing this with mypy highlights the value of MyEnum.a.value as Any. That makes sense, as enum member values could be of any type.
However, in this case I know that all members of my enum should have int values, and no other type. In general, in most cases where I have used an enum the values have all been of a single type. I'd like to communicate this to the typing system somehow, but it doesn't seem possible with enum.Enum.

Changing the enum's type to enum.IntEnum lets mypy identify the value as int, however, using IntEnum is discouraged by the enum module documentation since it also makes enums comparable to other enums and to integers, which wouldn't actually be necessary for this use case. So as far as I understand using IntEnum wouldn't be ideal either.

Casting the .value to an int works, but it's more a workaround than a solution, and I hope this could somehow be done without casting.

To me, it seems this could be solved by introducing a generic Enum type in typing, similar to Sequence[T] and the other generics defined there.
With this, the code would look like

from typing import Enum

class MyEnum(Enum[int]):
    a = 1
    b = 2

some_func(MyEnum.a.value)

This could make the intent of the enum more clear, and would allow people to catch errors that would be introduced by defining an enum member with a different value type. It also would allow static checkers to infer the type of the enum member's value without having to use casts. Comparison operations would work the same way as for enum.Enum, and unlike enum.IntEnum.

If something like this could be considered for the typing module I'd be very grateful.

(Also, lastly, thanks for all the work on static typing in Python. It's helped me catch several bugs in my code so far, and I'm working on fully converting my project to make use of static typing, since it's been such a great help so far.)

贡献指南

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

从这里开始

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

调研方向

未指定任何仓库文件、测试或实现入口点。首先应根据现有的 Enum 和 IntEnum 类型讨论,审查所提议的泛型 Enum[int] 行为;要完成这项工作,需要达成一致的设计,并为值类型推断和混合成员值提供相应的实现与测试。

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

评估

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

把新 issue 发到你的邮箱

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