【问题标题】:What are "Bootstrap issues" of functionls wraps decorator?什么是函数包装装饰器的“引导问题”?
【发布时间】:2012-07-31 19:19:11
【问题描述】:

Python 3.2 在reprlib 模块中引入了一个新函数recursive_repr

当我查看source code 时,我发现了这段代码:

def recursive_repr(fillvalue='...'):
    'Decorator to make a repr function return fillvalue for a recursive call'

    def decorating_function(user_function):
        repr_running = set()

        def wrapper(self):
            key = id(self), get_ident()
            if key in repr_running:
                return fillvalue
            repr_running.add(key)
            try:
                result = user_function(self)
            finally:
                repr_running.discard(key)
            return result

        # Can't use functools.wraps() here because of bootstrap issues
        wrapper.__module__ = getattr(user_function, '__module__')
        wrapper.__doc__ = getattr(user_function, '__doc__')
        wrapper.__name__ = getattr(user_function, '__name__')
        wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
        return wrapper

    return decorating_function

我不明白的是什么是引导问题,为什么不能将@wraps(user_function) 应用于wrapper

【问题讨论】:

    标签: python python-3.2 functools


    【解决方案1】:

    在我看来,“引导问题”来自循环依赖。在这种情况下,functools 导入 collections,而后者又导入 reprlib。如果reprlib 试图导入functools.wraps,它会隐式地尝试导入自己,这是行不通的。 Python programming FAQ(2.7,但我认为此后没有改变)表示当模块使用 from module import function 表单时循环导入将失败,这些模块会这样做。

    【讨论】:

      【解决方案2】:

      “Bootstrapping”指的是“用自己的bootstraps捡起自己”这句话,这显然是不可能的。在这种情况下,这意味着你不能在这里使用 wraps(),因为这个函数本身就是 wraps() 定义的一部分。

      【讨论】:

        猜你喜欢
        • 2011-06-25
        • 2011-06-24
        • 2018-01-02
        • 2017-11-05
        • 2016-11-25
        • 2018-11-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多