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

Does a "with" statement support type hinting?

你能为使用 with 语法定义的变量定义类型提示吗?

with example() as x:
    print(x)

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

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

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

我在 typing documentation 中找不到示例。

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

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

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

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

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

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