functools.wraps for python 2.4
-
30-06-2021 - |
Question
functools.wraps
is not available in python 2.4.Is there any other module which can be used instead of this in python 2.4?
La solution
You can copy the functools code from Python2.5 and have it work in Python2.4 with only minor changes (substitute a lambda for the partial): http://hg.python.org/cpython/file/b48e1b48e670/Lib/functools.py#l15
Here's a simple replacement for partial:
def partial(func, *args, **kwds):
"Emulate Python2.6's functools.partial"
return lambda *fargs, **fkwds: func(*(args+fargs), **dict(kwds, **fkwds))
Autres conseils
Elaborating on Raymond Hettinger's answer:
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)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow