functools.wraps
在python 2.4中不可用。在python 2.4中是否还有其他模块可用于代替?
答案 0 :(得分:7)
您可以从Python2.5复制functools代码并使其在Python2.4中工作,只需进行少量更改(用 lambda 代替 partial ):{{ 3}}
以下是partial的简单替代:
def partial(func, *args, **kwds):
"Emulate Python2.6's functools.partial"
return lambda *fargs, **fkwds: func(*(args+fargs), **dict(kwds, **fkwds))
答案 1 :(得分:0)
阐述Raymond Hettinger的回答:
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
def wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES):
def partial(func, *args, **kwds):
return lambda *fargs, **fkwds: func(*(args+fargs), **dict(kwds,**fkwds))
def update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS,
updated=WRAPPER_UPDATES):
for attr in assigned:
setattr(wrapper, attr, getattr(wrapped, attr))
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
return wrapper
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)