Introduce `typing.STRICTER_STUBS`
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 1.8k
- 派生
- 302
- 平均合并
- 23 小时
- 30 天内合并 PR
- 8
描述
Some functions can return different types depending on passed arguments. For example:
open(name, 'rb')returnsio.BufferedReader, whereasopen(name, 'wb')returnsio.BufferedWriter.
The typeshed accurately models this using @typing.overload and typing.Literal. However there is the case that the argument value deciding the return type cannot be determined statically, for example:
def my_open(name: str, write: bool):
with open(name, 'wb' if write else 'rb') as f:
content = f.read()
In this case typeshed currently just claims that open returns typing.IO[Any], so content ends up having the type Any, resulting in a loss of type safety (e.g. content.startswith('hello') will lead to a runtime error if the file was opened in binary mode, but type checkers won't be able to warn you about this because of Any).
While typeshed could theoretically just change the return type to typing.IO[Union[str, bytes]], that would force all existing code bases that currently rely on Any to type check to update their code, which is of course unacceptable.
When starting a new project I however want the strictest type stubs possible. I explicitly do not want standard library functions to return unsafe values like Any (or the a bit less unsafe AnyOf suggested in #566), when the return types can be modeled by a Union.
I therefore propose the introduction of a new variable typing.STRICTER_STUBS: bool, that's only available during type checking.
Which would allow typeshed to do the following:
if typing.STRICTER_STUBS:
AnyOrUnion = typing.Union
else:
AnyOrUnion = typing.Any
Ambiguous return types could then be annotated as e.g. -> typing.IO[AnyOrUnion[str, bytes]].
This would allow users to opt into stricter type stubs, if they so desire, without forcing changes on existing code bases.
CC: @AlexWaygood, @JelleZijlstra, @srittau, @hauntsaninja, @rchen152, @erictraut
P.S. Since I have seen Union return types being dismissed because "the caller needs to use isinstance()", I want to note that this is not true, if the caller wants to trade type safety for performance, they can always just add an explicit Any annotation to circumvent the runtime overhead of isinstance. Union return types force you to either handle potential type errors or explicitly opt out of type safety, which I find strongly preferable to lack of type safety by default.
贡献指南
这个仓库没有索引到贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先审查提议的 typing.STRICTER_STUBS 行为以及此 issue 中的讨论,包括对 #566 的引用。确定选择启用更严格返回类型时的兼容性和类型检查要求;由于没有确定源文件或测试,只有在达成一致的设计并制定实施计划后才能视为完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- devtools
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100