frame.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # encoding: utf-8
  2. """
  3. Utilities for working with stack frames.
  4. """
  5. #-----------------------------------------------------------------------------
  6. # Copyright (C) 2008-2011 The IPython Development Team
  7. #
  8. # Distributed under the terms of the BSD License. The full license is in
  9. # the file COPYING, distributed as part of this software.
  10. #-----------------------------------------------------------------------------
  11. #-----------------------------------------------------------------------------
  12. # Imports
  13. #-----------------------------------------------------------------------------
  14. import sys
  15. #-----------------------------------------------------------------------------
  16. # Code
  17. #-----------------------------------------------------------------------------
  18. def extract_vars(*names,**kw):
  19. """Extract a set of variables by name from another frame.
  20. Parameters
  21. ----------
  22. *names : str
  23. One or more variable names which will be extracted from the caller's
  24. frame.
  25. **kw : integer, optional
  26. How many frames in the stack to walk when looking for your variables.
  27. The default is 0, which will use the frame where the call was made.
  28. Examples
  29. --------
  30. ::
  31. In [2]: def func(x):
  32. ...: y = 1
  33. ...: print(sorted(extract_vars('x','y').items()))
  34. ...:
  35. In [3]: func('hello')
  36. [('x', 'hello'), ('y', 1)]
  37. """
  38. depth = kw.get('depth',0)
  39. callerNS = sys._getframe(depth+1).f_locals
  40. return dict((k,callerNS[k]) for k in names)
  41. def extract_vars_above(*names):
  42. """Extract a set of variables by name from another frame.
  43. Similar to extractVars(), but with a specified depth of 1, so that names
  44. are extracted exactly from above the caller.
  45. This is simply a convenience function so that the very common case (for us)
  46. of skipping exactly 1 frame doesn't have to construct a special dict for
  47. keyword passing."""
  48. callerNS = sys._getframe(2).f_locals
  49. return dict((k,callerNS[k]) for k in names)
  50. def debugx(expr,pre_msg=''):
  51. """Print the value of an expression from the caller's frame.
  52. Takes an expression, evaluates it in the caller's frame and prints both
  53. the given expression and the resulting value (as well as a debug mark
  54. indicating the name of the calling function. The input must be of a form
  55. suitable for eval().
  56. An optional message can be passed, which will be prepended to the printed
  57. expr->value pair."""
  58. cf = sys._getframe(1)
  59. print('[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
  60. eval(expr,cf.f_globals,cf.f_locals)))
  61. # deactivate it by uncommenting the following line, which makes it a no-op
  62. #def debugx(expr,pre_msg=''): pass
  63. def extract_module_locals(depth=0):
  64. """Returns (module, locals) of the function `depth` frames away from the caller"""
  65. f = sys._getframe(depth + 1)
  66. global_ns = f.f_globals
  67. module = sys.modules[global_ns['__name__']]
  68. return (module, f.f_locals)