“ with”语句是否支持类型提示?

时间:2020-02-11 13:30:10

标签: python python-3.x type-hinting

您可以为使用with语法定义的变量定义类型提示吗?

with example() as x:
    print(x)

我想在上面键入提示以表明xstr(作为示例)。

我发现的唯一解决方法是使用中间变量,但这感觉很麻烦。

with example() as x:
    y: str = x
    print(y)

我在typing documentation中找不到示例。

2 个答案:

答案 0 :(得分:15)

PEP 526(已在Python 3.6中实现)允许您注释变量。您可以使用例如

x: str
with example() as x:
    [...]

with example() as x:
    x: str
    [...]

答案 1 :(得分:14)

通常,类型注释位于API边界。在这种情况下,应从example.__enter__推断类型。如果该函数未声明任何类型,则解决方案是创建一个相应的stub file,以帮助类型检查器推断该类型。

具体来说,这意味着创建一个.pyi文件,该文件的茎与导入Example的模块的茎相同。然后可以添加以下代码:

class Example:
    def __enter__(self) -> str: ...
    def __exit__(self, exc_type, exc_value, exc_traceback) -> None: ...