frame.py 3.0 KB

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