How to properly annotate a ContextManager in PyCharm?

前端 未结 2 1514
走了就别回头了
走了就别回头了 2021-01-18 09:45

How can I annotate the yield type of a contextmanager in PyCharm so that it properly guesses the type of the value used in the with clauses - just

2条回答
  •  清酒与你
    2021-01-18 10:11

    I believe you can use ContextManager from typing, e.g.:

    import contextlib
    from typing import ContextManager
    from pathlib import Path
    
    
    @contextlib.contextmanager
    def temp_borders_file() -> ContextManager[Path]:
        pass
    
    
    with temp_borders_file() as borders_f:
        borders_f  # has type Path here
    

提交回复
热议问题