TypeGuard typechecking on `filter` is too strict

未关闭
#12,682 10 条评论 34 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
42/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
冷清
技术栈
python
领域
devtools

调研方向

使用提供的 filter-mypy.py 示例重现该报告,并检查 issue 中所示的 builtins.filter 重载,然后确定修复应归属于 mypy 还是 typeshed。只有在 None、bool 和 isinstance 的用法能够按预期通过类型检查,且不会削弱对无关 filter 用法的检查时,才算完成。

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

描述

bug topic-overloads topic-type-context topic-typeguard-typeis

Bug Report

NB: This may be more properly an issue in Typeshed, or require changes in that project to fix, but our team encountered it via MyPy.

The type annotations on builtins.filter cause correct and idiomatic usages to fail to typecheck:

To Reproduce

# filter-mypy.py
path_parts: List[Optional[str]] = ["foo", None, "bar"]

"/".join(filter(None, path_parts))
"/".join(filter(bool, path_parts))
"/".join(filter(lambda s: isinstance(s, str), path_parts))

Expected:

$> mypy filter-mypy.py
Success: no issues found in 1 source file

Actual result:

$> mypy filter-mypy.py
filter-mypy.py:6: error: Argument 1 to "filter" has incompatible type "Type[bool]"; expected "Callable[[Optional[str]], TypeGuard[str]]"
filter-mypy.py:7: error: Argument 1 to "filter" has incompatible type "Callable[[Any], bool]"; expected "Callable[[Optional[str]], TypeGuard[str]]"
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used:
$> mypy --version
mypy 0.950 (compiled: yes)
  • Python version used:
$> python --version
Python 3.10.4
  • Operating system and version: Ubuntu 20.04

The following is what my editor (VSCode) pulls up when I investigate the type hints for filter, though I doubt this is the same file that MyPy itself is consulting:

class filter(Iterator[_T], Generic[_T]):
    @overload
    def __init__(self, __function: None, __iterable: Iterable[_T | None]) -> None: ...
    @overload
    def __init__(self, __function: Callable[[_S], TypeGuard[_T]], __iterable: Iterable[_S]) -> None: ...
    @overload
    def __init__(self, __function: Callable[[_T], Any], __iterable: Iterable[_T]) -> None: ...

Note that both offending lines conform to the third type signature, but fail the second.

主要语言
Python
星标
20.6k
派生
3.3k
平均合并
1 天 18 小时
30 天内合并 PR
54

贡献指南

打开贡献指南

从这里开始

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

python/mypy 的其他 Issue

查看 python/mypy 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

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