python / python/typing

TypingError: type checker will emit error with a message specified in typing stubs

未关闭
#1,043 16 条评论 13 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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

描述

Some ways to call certain functions are just wrong, and are known to be a bug. For example, passing type=bool to argparse's add_argument method doesn't work. To make type checkers warn about this, typeshed can currently do something like this:

@overload
def add_argument(self, unrelated args, type: Type[bool], more unrelated args) -> NoReturn: ...
@overload
def add_argument(self, unrelated args) -> None: ...

When add_argument is used wrongly, you would then get errors:

import argparse
parser = argparse.ArgumentParser(description="My parser")
parser.add_argument("--my_bool", type=bool)
print(parser.parse_args())  # Error: statement is unreachable

This approach has a couple problems:

  • The type checker's error message doesn't say "you passed in type=bool and it's wrong". It says "statement is unreachable".
  • The type checker's error message appears on a different line than where the buggy code is.
  • Unreachable code warnings are disabled by default in mypy, even with --strict.

The solution I would like: if you declare the return type as TypingError["foo bar"], the type checker will display an error message foo bar. This is similar to how #error works in the C preprocessor.

Stub:

@overload
def add_argument(
    self, unrelated args, type: Type[bool], more unrelated args
) -> TypingError["type=bool doesn't work, see https://stackoverflow.com/q/15008758"]: ...
@overload
def add_argument(self, unrelated args) -> None: ...

Python file:

import argparse
parser = argparse.ArgumentParser(description="My parser")
parser.add_argument("--my_bool", type=bool)  # Error: type=bool doesn't work, see https://stackoverflow.com/q/15008758
print(parser.parse_args())

贡献指南

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

从这里开始

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

调研方向

先从本 issue 中 TypingError 的返回类型提案和 overload 示例开始,然后确定相关的 type-checker 或 typing-spec 入口点。完成的标准是:checker 在出错的调用位置报告所提供的消息,同时保留正常的 overload 行为。

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

评估

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

把新 issue 发到你的邮箱

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