我目前正在编写和学习装饰器(带参数和不带参数)。下面是一个带有一个参数的装饰器示例,它将函数的输出重定向到日志文件。该代码有效,但我的问题如下:
提前谢谢您!
def redirect_output(log_file):
"""
Decorator to redirect the stdout written output of a function to a specified
log file.
Args:
log_file (str): The path to the log file where the output will be redirected.
"""
def redirect_output_decorator(func):
@functools.wraps(func)
def redirect_output_wrapper(*args, **kwargs) -> Any:
output = StringIO()
with redirect_stdout(output):
func(*args, **kwargs)
output_lines = output.getvalue().splitlines()
if output_lines:
file_logger("Output from {}: ".format(func.__name__), log_file)
for line in output_lines:
file_logger(line, log_file, with_date=False)
return redirect_output_wrapper
return redirect_output_decorator
ParamSpec
就是这个问题的解决方案。
这是代码示例
在其文档中。
from typing import TypeVar, ParamSpec
import logging
T = TypeVar('T')
P = ParamSpec('P')
def add_logging(f: Callable[P, T]) -> Callable[P, T]:
'''A type-safe decorator to add logging to a function.'''
def inner(*args: P.args, **kwargs: P.kwargs) -> T:
logging.info(f'{f.__name__} was called')
return f(*args, **kwargs)
return inner
Python 3.10之后正式支持,但对于大于3.7的Python版本也可以通过从
typing_extensions
(https://github.com/python/typing_extensions)导入来支持