此功能类型是否正确注释?
import subprocess
from os import PathLike
from typing import Union, Sequence, Any
def run(shell_command: Union[bytes, str, Sequence[Union[bytes, str, PathLike]]], **subprocess_run_kwargs: Any) -> int:
return subprocess.run(shell_command, check=True, shell=True, **subprocess_run_kwargs).returncode
我猜它不是,因为我得到了:
he\other.py:6: error: Missing type parameters for generic type
要获得相同的错误,请将以上代码保存在other.py
中,然后:
$ pip install mypy
$ mypy --strict other.py
PathLike
是泛型类型,因此您需要将其与类型参数(例如AnyStr
)一起使用:
import subprocess
from os import PathLike
from typing import Union, Sequence, Any, AnyStr
def run(shell_command: Union[bytes, str, Sequence[Union[bytes, str, PathLike[AnyStr]]]], **subprocess_run_kwargs: Any) -> int:
return subprocess.run(shell_command, check=True, shell=True, **subprocess_run_kwargs).returncode
相关问题:
UPDATE
对不起,我没有在运行时检查此代码。通过一些技巧,可以编写一个变通方法:
import subprocess
from os import PathLike as BasePathLike
from typing import Union, Sequence, Any, AnyStr, TYPE_CHECKING
import abc
if TYPE_CHECKING:
PathLike = BasePathLike
else:
class FakeGenericMeta(abc.ABCMeta):
def __getitem__(self, item):
return self
class PathLike(BasePathLike, metaclass=FakeGenericMeta):
pass
def run(shell_command: Union[bytes, str, Sequence[Union[bytes, str, PathLike[AnyStr]]]], **subprocess_run_kwargs: Any) -> int:
return subprocess.run(shell_command, check=True, shell=True, **subprocess_run_kwargs).returncode
与此解决方法相关的问题: