Python type hints and context managers

后端 未结 4 1789
执念已碎
执念已碎 2020-12-15 15:05

How should a context manager be annotated with Python type hints?

import typing

@contextlib.contextmanager
def foo() -> ???:
    yield

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-15 15:52

    With my PyCharm, I do the following to make its type hinting work:

    from contextlib import contextmanager
    from typing import ContextManager
    
    @contextmanager
    def session() -> ContextManager[Session]:
        yield Session(...)
    

提交回复
热议问题