Answer a question

Is this function type-annotated correctly?

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

I'm guessing it's not, because I'm getting:

he\other.py:6: error: Missing type parameters for generic type

To get the same error, then save the above code in other.py, and then:

$ pip install mypy

$ mypy --strict other.py

Answers

PathLike is a generic type, so you need to use it with a type parameter (AnyStr for example):

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

Related issues:

  • https://github.com/python/mypy/issues/6112
  • https://github.com/python/mypy/issues/6128

UPDATE

Sorry, I didn't check this code at runtime. With some tricks it is possible to write a workaround:

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

Issues related to this workaround:

  • mypy: how to define a generic subclass
  • https://github.com/python/mypy/issues/5264
Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐