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