python / python/typeshed

Properties `.start`, `.stop`, `. step` of (generic) `slice[...]` should be optional (`| None`)

未关闭
#15,526 6 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
Python
星标
5.1k
派生
2.1k
平均合并
1 天 19 小时
30 天内合并 PR
82

描述

Situation

#13008 made slice.__new__ more precise. Generic slice[T] accepts T | None as arguments when creating a slice.
However, properties .start, .stop, . step of (generic) slice[...] are typed as there respective types, i.e. T in above example.

Consequence

This leads to typecheckers accepting:

def test(s: slice[int]) -> None:
    assert_type(s.start, int)
    if s.start is None:
        assert_never(s.start)

whereas below obviously breaks:

test(slice(42))

Solution

Therefore, I suggest properties .start, .stop, . step should have optional (| None) return types:

    @property
    def start(self) -> _StartT_co | None: ...
    @property
    def step(self) -> _StepT_co | None: ...
    @property
    def stop(self) -> _StopT_co | None: ...

Alternative

Currently, typeshed uses slice[...] as slice[T | None] explicitly as per #13007, e.g.

class str:
    def __getitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> str: ...

While that works/typechecks correctly:

def test(s: slice[int | None]) -> None:
    assert_type(s.start, int | None)
    if s.start is None or isinstance(s.start, int):
        pass
    else:
        assert_never(s.start)

test(slice(42))   # okay
test(slice('x'))  # error: Argument 1 to "slice" has incompatible type "str"; expected "int | None"  [arg-type]

I see as downsides:

  1. it's error-prone / less ergonomic
  2. it renders part of #13008 __new__ overloading complexity superfluous
  3. it made #13007 more complex

Question

@Sachaa-Thanasius: Was the proposed solution considered for #13007?

贡献指南

打开贡献指南

从这里开始

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

调研方向

从 typeshed 的通用 slice stub 开始,结合 #13007 中的替代方案,检查 #13008 讨论的 new 注解。将 issue 中的 slice(42) 示例与 .start、.stop 和 .step 的类型进行对照;当注解保留 None 且所示的类型检查行为正确时即完成。

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

评估

技术栈
python
领域
devtools
Issue 类型
缺陷
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
基本清楚
新手友好度
55/100

把新 issue 发到你的邮箱

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