如何正确将类型提示添加到装饰器?

时间:2019-09-11 13:53:49

标签: python python-decorators type-hinting

我目前正在撰写和学习装饰器(带有或不带有参数)。这是带有一个参数的修饰器的示例,该修饰符将函数的输出重定向到日志文件。该代码有效,但是我的问题如下:

  1. 与装饰器打交道时使用类型提示的正确方法是什么?
  2. 装饰器是否应该具有文档字符串?如果是这样,在我的示例中,文档字符串正确/完整吗?

提前谢谢!

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

0 个答案:

没有答案