Wrapper around a Python frame holding f_locals and f_globals in which expressions can be evaluated.
| 130 | |
| 131 | |
| 132 | class Frame: |
| 133 | """Wrapper around a Python frame holding f_locals and f_globals |
| 134 | in which expressions can be evaluated.""" |
| 135 | |
| 136 | __slots__ = ("raw",) |
| 137 | |
| 138 | def __init__(self, frame: FrameType) -> None: |
| 139 | self.raw = frame |
| 140 | |
| 141 | @property |
| 142 | def lineno(self) -> int: |
| 143 | return self.raw.f_lineno - 1 |
| 144 | |
| 145 | @property |
| 146 | def f_globals(self) -> dict[str, Any]: |
| 147 | return self.raw.f_globals |
| 148 | |
| 149 | @property |
| 150 | def f_locals(self) -> dict[str, Any]: |
| 151 | return self.raw.f_locals |
| 152 | |
| 153 | @property |
| 154 | def code(self) -> Code: |
| 155 | return Code(self.raw.f_code) |
| 156 | |
| 157 | @property |
| 158 | def statement(self) -> Source: |
| 159 | """Statement this frame is at.""" |
| 160 | if self.code.fullsource is None: |
| 161 | return Source("") |
| 162 | return self.code.fullsource.getstatement(self.lineno) |
| 163 | |
| 164 | def eval(self, code, **vars): |
| 165 | """Evaluate 'code' in the frame. |
| 166 | |
| 167 | 'vars' are optional additional local variables. |
| 168 | |
| 169 | Returns the result of the evaluation. |
| 170 | """ |
| 171 | f_locals = self.f_locals.copy() |
| 172 | f_locals.update(vars) |
| 173 | return eval(code, self.f_globals, f_locals) |
| 174 | |
| 175 | def repr(self, object: object) -> str: |
| 176 | """Return a 'safe' (non-recursive, one-line) string repr for 'object'.""" |
| 177 | return saferepr(object) |
| 178 | |
| 179 | def getargs(self, var: bool = False): |
| 180 | """Return a list of tuples (name, value) for all arguments. |
| 181 | |
| 182 | If 'var' is set True, also include the variable and keyword arguments |
| 183 | when present. |
| 184 | """ |
| 185 | retval = [] |
| 186 | for arg in self.code.getargs(var): |
| 187 | try: |
| 188 | retval.append((arg, self.f_locals[arg])) |
| 189 | except KeyError: |
no outgoing calls