Python 3.2在recursive_repr
模块中引入了一个新函数reprlib
。
当我查看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
我不明白的是什么是Bootstrap问题以及为什么不能将@wraps(user_function)
应用于wrapper
?
在我看来,“引导问题”来自循环依赖。在这种情况下,functools
进口collections
,反过来进口reprlib
。如果reprlib
试图导入functools.wraps
,它将隐含地尝试导入自己,这是行不通的。 Python programming FAQ(2.7,但我认为此后没有改变)说当模块使用from module import function
形式时,循环导入将失败,这些模块就是这样做的。
“Bootstrapping”是指“通过自己的引导自我”这一短语,这显然是不可能的。在这种情况下,它意味着你不能在这里使用wraps(),因为这个函数本身就是wrapps()定义的一部分。