此函数类型注释是否正确?

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

相关问题:
  • https://github.com/python/mypy/issues/6112
  • https://github.com/python/mypy/issues/6128

  • 更新

    抱歉,我没有在运行时检查此代码。通过一些技巧,可以编写解决方法:
    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
    

    与此解决方法相关的问题:
  • mypy: how to define a generic subclass
  • https://github.com/python/mypy/issues/5264
  • 关于python - 为什么这个函数类型注释不正确(错误 : Missing type parameters for generic type)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55076778/

    10-12 07:34
    查看更多