为什么这个函数没有正确注释(错误:泛型类型缺少类型参数)?

问题描述 投票:1回答:1

此功能类型是否正确注释?

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
python python-3.x mypy
1个回答
1
投票

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

与此解决方法相关的问题:

© www.soinside.com 2019 - 2024. All rights reserved.