decorators.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # encoding: utf-8
  2. """Decorators that don't go anywhere else.
  3. This module contains misc. decorators that don't really go with another module
  4. in :mod:`IPython.utils`. Beore putting something here please see if it should
  5. go into another topical module in :mod:`IPython.utils`.
  6. """
  7. #-----------------------------------------------------------------------------
  8. # Copyright (C) 2008-2011 The IPython Development Team
  9. #
  10. # Distributed under the terms of the BSD License. The full license is in
  11. # the file COPYING, distributed as part of this software.
  12. #-----------------------------------------------------------------------------
  13. #-----------------------------------------------------------------------------
  14. # Imports
  15. #-----------------------------------------------------------------------------
  16. #-----------------------------------------------------------------------------
  17. # Code
  18. #-----------------------------------------------------------------------------
  19. def flag_calls(func):
  20. """Wrap a function to detect and flag when it gets called.
  21. This is a decorator which takes a function and wraps it in a function with
  22. a 'called' attribute. wrapper.called is initialized to False.
  23. The wrapper.called attribute is set to False right before each call to the
  24. wrapped function, so if the call fails it remains False. After the call
  25. completes, wrapper.called is set to True and the output is returned.
  26. Testing for truth in wrapper.called allows you to determine if a call to
  27. func() was attempted and succeeded."""
  28. # don't wrap twice
  29. if hasattr(func, 'called'):
  30. return func
  31. def wrapper(*args,**kw):
  32. wrapper.called = False
  33. out = func(*args,**kw)
  34. wrapper.called = True
  35. return out
  36. wrapper.called = False
  37. wrapper.__doc__ = func.__doc__
  38. return wrapper
  39. def undoc(func):
  40. """Mark a function or class as undocumented.
  41. This is found by inspecting the AST, so for now it must be used directly
  42. as @undoc, not as e.g. @decorators.undoc
  43. """
  44. return func