Annotating functions which don't raise exceptions
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 1.8k
- 派生
- 302
- 平均合并
- 23 小时
- 30 天内合并 PR
- 8
描述
I would find it interesting to be able to annotate functions which never throw exceptions. "Never" can be either in the absolute sense, or in the sense of "checked exceptions", with some subset of exception designated as "unchecked" (details of this designation are perhaps up to the actual tool to process annotations).
Example of a function which absolutely never raises exceptions (well, at least per language semantics, particular implementations might still have means to break with some implementation-related exceptions):
def foo(l):
if isinstance(l, list) and len(l) > 0:
return l[0]
Example of a function which may throw (unchecked) exception if API contract is violated:
def foo(l: list):
if len(l) > 0:
return l[0]
So, hopefully these examples show that the notion does exist in Python.
Now the question how to annotate it. Following the existing NoReturn, it would be called NoRaise or NoThrow. "nothrow" terminology if familiar from C++ (and it seems to be replaced even there), so perhaps sticking with native Python terminology makes sense (but "throw" is native to Python too, re: exception handling with generators).
More interesting question is where to put that annotation. Taking the example above, a natural annotation would be:
def foo(l) -> Optional(Any), NoRaise:
And I was quite surprised that the usual "implicit tuple" syntax rule doesn't apply here, and the above is SyntaxError as of CPy3.7:
Python 3.7.1 (default, Oct 22 2018, 11:21:55)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo() -> list, int:
File "<stdin>", line 1
def foo() -> list, int:
^
SyntaxError: invalid syntax
I wonder if that warrants a separate issue report. And whether it was a cunning design choice mere mortals need to decipher, because that seems too obvious thing to overlook with an implicit tuple syntax, again (neither problematic from forma grammar perspective, even in LL it's "->" expr ("," expr)* ":", which is trivial, Python has more complex grammar rules in many places.
So, all in all, now it would need to be written as:
def foo(l) -> (Optional(Any), NoRaise):
Which is of course not as pretty as without parens.
贡献指南
这个仓库没有索引到贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
没有指定仓库文件或测试。首先查看现有的 NoReturn 注解以及这里描述的 Python 3.7 语法行为,然后明确目标是异常语义、注解语法,还是两者兼有。完成此项工作需要就 NoRaise 或 NoThrow 的含义达成一致,并指定有效的语法。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- devtools
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 需要澄清
- 新手友好度
- 25/100