这个装饰器的类型注释是否正确?
Is this decorator type-annotated correctly?
from functools import wraps
from typing import Any, Callable
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
这里的缩进似乎有点不对,但除此之外,是的,类型并没有错。不过,您可以使它更精确一些。您输出的函数与作为输入的函数具有相同的 return 类型,但您没有注意到这一点。
具体来说,你可以这样说
from typing import Callable, TypeVar
T = TypeVar("T")
def timer(func: Callable[..., T]) -> Callable[..., T]:
看来您应该可以对 args/kwargs 执行相同的操作,但根据我自己的打字经验,我还没有遇到过这种情况,所以我不能确切地说出具体方法。编辑 - 有关输入这些内容的更多信息,请参阅 this GitHub issue;似乎不可能(还?)。
我想你也可以说
def timer(func: T) -> T:
但这似乎没什么用。
这种方法的问题是,现在 MyPy 失去了 return 类型,或者更确切地说,它退化为 Any
,因此请考虑:
import logging
from typing import Callable, Any
from time import perf_counter
from functools import wraps
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
@timer
def func(x:int) -> int:
return x
def string_func(s: str):
return s[:]
x = 42 * func(42)
reveal_type(x)
string_func(x)
使用:
(py37) Juans-MacBook-Pro:tempdata juan$ mypy --version
mypy 0.641
如果我尝试对此进行类型检查,它会通过!
(py37) Juans-MacBook-Pro:tempdata juan$ mypy typing_decorators.py
typing_decorators.py:29: error: Revealed type is 'Any'
如果您想 完全保留 参数,我找到了一种解决方案,即使用 TypeVar
和 cast
包装器,这样 MyPy 就可以准确地知道类型(假设原始函数被注释):
import logging
from typing import Callable, Any, TypeVar, cast
from time import perf_counter
from functools import wraps
F = TypeVar('F', bound=Callable[..., Any])
def timer(func: F) -> F:
"""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 cast(F, wrapper)
@timer
def func(x:int) -> int:
return x
def string_func(s: str):
return s[:]
x = 42 * func(42)
reveal_type(x)
string_func(x)
在这种情况下:
(py37) Juans-MacBook-Pro:tempdata juan$ mypy typing_decorators.py
typing_decorators.py:32: error: Revealed type is 'builtins.int'
typing_decorators.py:34: error: Argument 1 to "string_func" has incompatible type "int"; expected "str"
from functools import wraps
from typing import Any, Callable
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
这里的缩进似乎有点不对,但除此之外,是的,类型并没有错。不过,您可以使它更精确一些。您输出的函数与作为输入的函数具有相同的 return 类型,但您没有注意到这一点。
具体来说,你可以这样说
from typing import Callable, TypeVar
T = TypeVar("T")
def timer(func: Callable[..., T]) -> Callable[..., T]:
看来您应该可以对 args/kwargs 执行相同的操作,但根据我自己的打字经验,我还没有遇到过这种情况,所以我不能确切地说出具体方法。编辑 - 有关输入这些内容的更多信息,请参阅 this GitHub issue;似乎不可能(还?)。
我想你也可以说
def timer(func: T) -> T:
但这似乎没什么用。
这种方法的问题是,现在 MyPy 失去了 return 类型,或者更确切地说,它退化为 Any
,因此请考虑:
import logging
from typing import Callable, Any
from time import perf_counter
from functools import wraps
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
@timer
def func(x:int) -> int:
return x
def string_func(s: str):
return s[:]
x = 42 * func(42)
reveal_type(x)
string_func(x)
使用:
(py37) Juans-MacBook-Pro:tempdata juan$ mypy --version
mypy 0.641
如果我尝试对此进行类型检查,它会通过!
(py37) Juans-MacBook-Pro:tempdata juan$ mypy typing_decorators.py
typing_decorators.py:29: error: Revealed type is 'Any'
如果您想 完全保留 参数,我找到了一种解决方案,即使用 TypeVar
和 cast
包装器,这样 MyPy 就可以准确地知道类型(假设原始函数被注释):
import logging
from typing import Callable, Any, TypeVar, cast
from time import perf_counter
from functools import wraps
F = TypeVar('F', bound=Callable[..., Any])
def timer(func: F) -> F:
"""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 cast(F, wrapper)
@timer
def func(x:int) -> int:
return x
def string_func(s: str):
return s[:]
x = 42 * func(42)
reveal_type(x)
string_func(x)
在这种情况下:
(py37) Juans-MacBook-Pro:tempdata juan$ mypy typing_decorators.py
typing_decorators.py:32: error: Revealed type is 'builtins.int'
typing_decorators.py:34: error: Argument 1 to "string_func" has incompatible type "int"; expected "str"