/Lib/functools.py

http://unladen-swallow.googlecode.com/ · Python · 51 lines · 17 code · 4 blank · 30 comment · 2 complexity · cf6d0efcf8e5cfb9f28953226dd3c120 MD5 · raw file

  1. """functools.py - Tools for working with functions and callable objects
  2. """
  3. # Python module wrapper for _functools C module
  4. # to allow utilities written in Python to be added
  5. # to the functools module.
  6. # Written by Nick Coghlan <ncoghlan at gmail.com>
  7. # Copyright (C) 2006 Python Software Foundation.
  8. # See C source code for _functools credits/copyright
  9. from _functools import partial, reduce
  10. # update_wrapper() and wraps() are tools to help write
  11. # wrapper functions that can handle naive introspection
  12. WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
  13. WRAPPER_UPDATES = ('__dict__',)
  14. def update_wrapper(wrapper,
  15. wrapped,
  16. assigned = WRAPPER_ASSIGNMENTS,
  17. updated = WRAPPER_UPDATES):
  18. """Update a wrapper function to look like the wrapped function
  19. wrapper is the function to be updated
  20. wrapped is the original function
  21. assigned is a tuple naming the attributes assigned directly
  22. from the wrapped function to the wrapper function (defaults to
  23. functools.WRAPPER_ASSIGNMENTS)
  24. updated is a tuple naming the attributes of the wrapper that
  25. are updated with the corresponding attribute from the wrapped
  26. function (defaults to functools.WRAPPER_UPDATES)
  27. """
  28. for attr in assigned:
  29. setattr(wrapper, attr, getattr(wrapped, attr))
  30. for attr in updated:
  31. getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
  32. # Return the wrapper so this can be used as a decorator via partial()
  33. return wrapper
  34. def wraps(wrapped,
  35. assigned = WRAPPER_ASSIGNMENTS,
  36. updated = WRAPPER_UPDATES):
  37. """Decorator factory to apply update_wrapper() to a wrapper function
  38. Returns a decorator that invokes update_wrapper() with the decorated
  39. function as the wrapper argument and the arguments to wraps() as the
  40. remaining arguments. Default arguments are as for update_wrapper().
  41. This is a convenience function to simplify applying partial() to
  42. update_wrapper().
  43. """
  44. return partial(update_wrapper, wrapped=wrapped,
  45. assigned=assigned, updated=updated)