Debian Codegraph @

pyinstrument/magic/_utils.py

raw symbols SCIP
1 from __future__ import annotations
2
3 # This file is largely based on https://gist.github.com/Carreau/0f051f57734222da925cd364e59cc17e which is in the public domain
4 # This (or something similar) may eventually be moved into IPython
5 import ast
6 from ast import Assign, Expr, Load, Name, NodeTransformer, Store, parse
7 from textwrap import dedent
8
9
10 class PrePostAstTransformer(NodeTransformer):
11 """
12 Allow to safely wrap user code with pre/post execution hooks that
13 run just before and just after usercode, __inside__ the execution loop,
14 But still returns the value of the last Expression.
15
16 This might not behave as expected if the user change the InteractiveShell.ast_node_interactivity option.
17
18 This is currently not hygienic and care must be taken to use uncommon names in the pre/post block.
19
20 Assuming the user have
21
22 ```
23 code_block:
24 [with many expressions]
25 last_expression
26 ```
27
28 It will transform it into
29
30 ```
31 try:
32 pre_block
33 code_block:
34 [with many expressions]
35 return_value = last_expression
36 finally:
37 post_block
38 return_value
39 ```
40
41 Thus making sure that post is always executed even if pre or user code fails.
42 """
43
44 def __init__(self, pre: str | ast.Module, post: str | ast.Module):
45 """
46 pre and post are either strings, or ast.Modules object that need to be run just before or after
47 the user code.
48
49 While strings are possible, we suggest using ast.Modules
50 object and mangling the corresponding variable names
51 to be invalid python identifiers to avoid name conflicts.
52 """
53 if isinstance(pre, str):
54 pre = parse(pre)
55 if isinstance(post, str):
56 post = parse(post)
57
58 self.pre = pre.body
59 self.post = post.body
60 self.active = True
61
62 def reset(self):
63 self.core = parse(
64 dedent(
65 """
66 try:
67 pass
68 finally:
69 pass
70 """
71 )
72 )
73 self.try_ = self.core.body[0].body = [] # type: ignore
74 self.fin = self.core.body[0].finalbody = [] # type: ignore
75
76 def visit_Module(self, node: ast.Module):
77 if not self.active:
78 return node
79 self.reset()
80 last = node.body[-1]
81 ret = None
82 if isinstance(last, Expr):
83 node.body.pop()
84 node.body.append(Assign([Name("ast-tmp", ctx=Store())], value=last.value))
85 ret = Expr(value=Name("ast-tmp", ctx=Load()))
86 # self.core.body.insert(0, Assign([Name('_p', ctx=Store())], value=ast.Constant(None) ))
87 if ret:
88 self.core.body.insert(
89 0, Assign([Name("ast-tmp", ctx=Store())], value=ast.Constant(None))
90 )
91 for p in self.pre + node.body:
92 self.try_.append(p)
93 for p in self.post:
94 self.fin.append(p)
95 if ret is not None:
96 self.core.body.append(ret)
97
98 ast.fix_missing_locations(self.core)
99 return self.core