frame.py 3.1 KB

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