【发布时间】:2018-09-18 21:31:13
【问题描述】:
上下文管理器应该如何使用 Python 类型提示进行注释?
import typing
@contextlib.contextmanager
def foo() -> ???:
yield
documentation on contextlib 没有过多提及类型。
documentation on typing.ContextManager 也不是很有帮助。
还有typing.Generator,至少有一个例子。这是否意味着我应该使用typing.Generator[None, None, None] 而不是typing.ContextManager?
import typing
@contextlib.contextmanager
def foo() -> typing.Generator[None, None, None]:
yield
【问题讨论】:
-
它是一个生成器,它产生、发送和返回
None,所以它是Generator[None, None, None]。是否将它用于上下文管理器并不重要。 -
如果你对这个特定的上下文管理器的用途有任何想法,你可以为预期的类型进行注释,否则你几乎可以接受任何东西(甚至没有)
-
在我的具体情况下,我只想使用上下文管理器进行日志记录(计时),因此产量、发送和返回值确实是
None。