小编Lau*_*che的帖子

为什么此函数类型注释不正确(错误:泛型类型缺少类型参数)?

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

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)

python python-3.x mypy

7
推荐指数
2
解决办法
4395
查看次数

如何对具有可选参数的装饰器进行类型注释?

这是我尝试正确键入注释的确切函数:

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)

python python-3.x mypy

6
推荐指数
1
解决办法
1435
查看次数

这个装饰器的类型标注正确吗?

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)

python python-3.x mypy

-3
推荐指数
2
解决办法
164
查看次数

标签 统计

mypy ×3

python ×3

python-3.x ×3