此函数类型注释是否正确?
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
Run Code Online (Sandbox Code Playgroud)
我猜不是,因为我得到:
he\other.py:6: error: Missing type parameters for generic type
要得到同样的错误,然后将上面的代码保存在 中other.py,然后:
$ pip install mypy
$ mypy --strict other.py
Run Code Online (Sandbox Code Playgroud) 这是我尝试正确键入注释的确切函数:
F = TypeVar('F', bound=Callable[..., Any])
def throttle(_func: Optional[F] = None, *, rate: float = 1) -> Union[F, Callable[[F], F]]:
"""Throttles a function call, so that at minimum it can be called every `rate` seconds.
Usage::
# this will enforce the default minimum time of 1 second between function calls
@throttle
def ...
or::
# this will enforce a custom minimum time of 2.5 seconds between function calls
@throttle(rate=2.5)
def ...
This will raise an error, because `rate=` needs to …Run Code Online (Sandbox Code Playgroud) def timer(func: Callable[..., Any]) -> Callable[..., Any]:
"""Calculates the runtime of a function, and outputs it to logging.DEBUG."""
@wraps(func)
def wrapper(*args, **kwargs):
start = perf_counter()
value = func(*args, **kwargs)
end = perf_counter()
_logger = logging.getLogger(__name__ + '.' + func.__name__)
_logger.debug(' runtime: {:.4f} seconds'.format(end - start))
return value
return wrapper
Run Code Online (Sandbox Code Playgroud)