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
?
最佳答案
在我看来,“ Bootstrap 问题”似乎来自循环依赖。在这种情况下,functools
进口collections
,它又导入 reprlib
。如果 reprlib
尝试导入 functools.wraps
,它会暗中尝试导入自身,这是行不通的。 Python programming FAQ (2.7,但我认为此后没有改变)说当模块使用 from module import function
形式时,循环导入将失败,这些模块就是这样做的。
关于python - 函数包装装饰器的 "Bootstrap issues"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11747412/