上下文管理器处理路径上的类型提示
Type hinting on a context manager processing paths
代码(在@juanpa.arrivillaga的帮助下修复:
"""Helpers that can be used for context management."""
import logging
import os
from contextlib import contextmanager
from pathlib import Path
from typing import Union, Iterator, Optional
_LOGGER = logging.getLogger(__name__)
@contextmanager
def working_directory(temporary_path: Union[Path, str], initial_path: Optional[Union[Path, str]] = None) -> Iterator[None]:
"""Changes working directory, and returns to `initial_path` on exit. It's needed for PRAW for example,
because it looks for praw.ini in Path.cwd(), but that file could be kept in a different directory.
`initial_path` can be used for example to change working directory relative to the script path, or
to end up in a different directory than Path.cwd() of the calling script.
Inspiration:
"""
_LOGGER.debug('Working directory of the calling script: %s', Path.cwd())
_LOGGER.debug('temporary_path = %s', temporary_path)
_LOGGER.debug('initial_path = %s', initial_path)
if not isinstance(temporary_path, (Path, str)):
raise TypeError('"temporary_path" is not of type `Path` or `str`')
if initial_path is None:
initial_path = Path.cwd()
else:
initial_path = Path(initial_path).absolute()
if not initial_path.is_dir():
initial_path = initial_path.parent
try:
os.chdir(initial_path / temporary_path)
_LOGGER.debug('Temporarily changed working directory to: %s', Path.cwd())
yield
finally:
os.chdir(initial_path)
我输入的注释是否正确?
另外,有没有更pythonic的方式来写这个函数?你会改变什么?我也会 post 它在 CodeReview 中。
打字没问题,您只是在代码中发现了 mypy 的错误。如果 initial_path
和 temporary_path
都是 str
那么这将失败。这就是它抱怨的原因。
你只在一个分支中转换为 Path
你没有 else
(不好的做法,IMO),所以当你到达行时:
initial_path / temporary_path
可能 两者都是 str
。
注意,mypy
不知道这个,但是if initial_path is not Path.cwd()
是不正确的。该语句将始终为 False。不要将事物与 is
进行比较,除非你指的是对象标识,在这种情况下,你不需要。
考虑:
>>> from pathlib import Path
>>> Path().cwd() is Path().cwd()
False
就这样:
def working_directory(
temporary_path: Union[Path, str],
initial_path: Union[Path, str] = Path.cwd()
) -> Iterator[None]:
temporary_path = Path(temporary_path)
initial_path = Path(initial_path)
在函数的开头。
代码(在@juanpa.arrivillaga的帮助下修复:
"""Helpers that can be used for context management."""
import logging
import os
from contextlib import contextmanager
from pathlib import Path
from typing import Union, Iterator, Optional
_LOGGER = logging.getLogger(__name__)
@contextmanager
def working_directory(temporary_path: Union[Path, str], initial_path: Optional[Union[Path, str]] = None) -> Iterator[None]:
"""Changes working directory, and returns to `initial_path` on exit. It's needed for PRAW for example,
because it looks for praw.ini in Path.cwd(), but that file could be kept in a different directory.
`initial_path` can be used for example to change working directory relative to the script path, or
to end up in a different directory than Path.cwd() of the calling script.
Inspiration:
"""
_LOGGER.debug('Working directory of the calling script: %s', Path.cwd())
_LOGGER.debug('temporary_path = %s', temporary_path)
_LOGGER.debug('initial_path = %s', initial_path)
if not isinstance(temporary_path, (Path, str)):
raise TypeError('"temporary_path" is not of type `Path` or `str`')
if initial_path is None:
initial_path = Path.cwd()
else:
initial_path = Path(initial_path).absolute()
if not initial_path.is_dir():
initial_path = initial_path.parent
try:
os.chdir(initial_path / temporary_path)
_LOGGER.debug('Temporarily changed working directory to: %s', Path.cwd())
yield
finally:
os.chdir(initial_path)
我输入的注释是否正确?
另外,有没有更pythonic的方式来写这个函数?你会改变什么?我也会 post 它在 CodeReview 中。
打字没问题,您只是在代码中发现了 mypy 的错误。如果 initial_path
和 temporary_path
都是 str
那么这将失败。这就是它抱怨的原因。
你只在一个分支中转换为 Path
你没有 else
(不好的做法,IMO),所以当你到达行时:
initial_path / temporary_path
可能 两者都是 str
。
注意,mypy
不知道这个,但是if initial_path is not Path.cwd()
是不正确的。该语句将始终为 False。不要将事物与 is
进行比较,除非你指的是对象标识,在这种情况下,你不需要。
考虑:
>>> from pathlib import Path
>>> Path().cwd() is Path().cwd()
False
就这样:
def working_directory(
temporary_path: Union[Path, str],
initial_path: Union[Path, str] = Path.cwd()
) -> Iterator[None]:
temporary_path = Path(temporary_path)
initial_path = Path(initial_path)
在函数的开头。