Debian Codegraph @

doc/extending.rst

raw
1 Extending astroid syntax tree
2 =============================
3
4 Sometimes astroid will miss some potentially important information
5 you may wish it supported instead, for instance with the libraries that rely
6 on dynamic features of the language. In some other cases, you may
7 want to customize the way inference works, for instance to explain **astroid**
8 that calls to `collections.namedtuple` are returning a class with some known
9 attributes.
10
11
12 Modifications in the AST are possible in a couple of ways.
13
14 AST transforms
15 ^^^^^^^^^^^^^^
16
17 **astroid** has support for AST transformations, which given a node,
18 should return either the same node but modified, or a completely new node.
19
20 The transform functions needs to be registered with the underlying manager,
21 that is, a class that **astroid** uses internally for all things configuration
22 related. You can access the manager using `astroid.MANAGER`.
23
24 The transform functions need to receive three parameters, with the third one
25 being optional:
26
27 * the type of the node for which the transform will be applied
28
29 * the transform function itself
30
31 * optionally, but strongly recommended, a transform predicate function.
32 This function receives the node as an argument and it is expected to
33 return a boolean specifying if the transform should be applied to this node
34 or not.
35
36 AST transforms - example
37 ------------------------
38
39 Let's see some examples!
40
41 Say that we love the new Python 3.6 feature called ``f-strings``, you might have
42 heard of them and now you want to use them in your Python 3.6+ project as well.
43
44 So instead of ``"your name is {}".format(name)"`` we'd want to rewrite this to
45 ``f"your name is {name}"``.
46
47 One thing you could do with astroid is that you can rewrite partially a tree
48 and then dump it back on disk to get the new modifications. Let's see an
49 example in which we rewrite our code so that instead of using ``.format()`` we'll
50 use f-strings instead.
51
52 While there are some technicalities to be aware of, such as the fact that
53 astroid is an AST (abstract syntax tree), while for code round-tripping you
54 might want a CST instead (concrete syntax tree), for the purpose of this example
55 we'll just consider all the round-trip edge cases as being irrelevant.
56
57 First of all, let's write a simple function that receives a node and returns
58 the same node unmodified::
59
60 def format_to_fstring_transform(node):
61 return node
62
63 astroid.MANAGER.register_transform(...)
64
65
66 For the registration of the transform, we are most likely interested in registering
67 it for ``astroid.Call``, which is the node for function calls, so this now becomes::
68
69 def format_to_fstring_transform(node):
70 return node
71
72 astroid.MANAGER.register_transform(
73 astroid.Call,
74 format_to_fstring_transform,
75 )
76
77 The next step would be to do the actual transformation, but before dwelving
78 into that, let's see some important concepts that nodes in astroid have:
79
80 * they have a parent. Every time we build a node, we have to provide a parent
81
82 * most of the time they have a line number and a column offset as well
83
84 * a node might also have children that are nodes as well. You can check what
85 a node needs if you access its ``_astroid_fields``, ``_other_fields``, ``_other_other_fields``
86 properties. They are all tuples of strings, where the strings depicts attribute names.
87 The first one is going to contain attributes that are nodes (so basically children
88 of a node), the second one is going to contain non-AST objects (such as strings or
89 other objects), while the third one can contain both AST and non-AST objects.
90
91 When instantiating a node, the non-AST parameters are usually passed via the
92 constructor, while the AST parameters are provided via the ``postinit()`` method.
93 The only exception is that the parent is also passed via the constructor.
94 Instantiating a new node might look as in::
95
96 new_node = FunctionDef(
97 name='my_new_function',
98 lineno=3,
99 col_offset=0,
100 parent=the_parent_of_this_function,
101 )
102 new_node.postinit(
103 args=args,
104 body=body,
105 returns=returns,
106 doc_node=nodes.Const(value='the docstring of this function'),
107 )
108
109
110 Now, with this knowledge, let's see how our transform might look::
111
112
113 def format_to_fstring_transform(node):
114 f_string_node = astroid.JoinedStr(
115 lineno=node.lineno,
116 col_offset=node.col_offset,
117 parent=node.parent,
118 )
119 formatted_value_node = astroid.FormattedValue(
120 lineno=node.lineno,
121 col_offset=node.col_offset,
122 parent=node.parent,
123 )
124 formatted_value_node.postinit(value=node.args[0])
125
126 # Removes the {} since it will be represented as
127 # formatted_value_node
128 string = astroid.Const(node.func.expr.value.replace('{}', ''))
129
130 f_string_node.postinit(values=[string, formatted_value_node])
131 return f_string_node
132
133 astroid.MANAGER.register_transform(
134 astroid.Call,
135 format_to_fstring_transform,
136 )
137
138
139 There are a couple of things going on, so let's see what we did:
140
141 * ``JoinedStr`` is used to represent the f-string AST node.
142
143 The catch is that the ``JoinedStr`` is formed out of the strings
144 that don't contain a formatting placeholder, followed by the ``FormattedValue``
145 nodes, which contain the f-strings formatting placeholders.
146
147 * ``node.args`` will hold a list of all the arguments passed in our function call,
148 so ``node.args[0]`` will actually point to the name variable that we passed.
149
150 * ``node.func.expr`` will be the string that we use for formatting.
151
152 * We call ``postinit()`` with the value being the aforementioned name. This will result
153 in the f-string being now complete.
154
155 You can now check to see if your transform did its job correctly by getting the
156 string representation of the node::
157
158 from astroid import parse
159 tree = parse('''
160 "my name is {}".format(name)
161 ''')
162 print(tree.as_string())
163
164 The output should print ``f"my name is {name}"``, and that's how you do AST transformations
165 with astroid!
166
167 AST inference tip transforms
168 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
169
170 Another interesting transform you can do with the AST is to provide the
171 so called ``inference tip``. **astroid** can be used as more than an AST library,
172 it also offers some basic support of inference, it can infer what names might
173 mean in a given context, it can be used to solve attributes in a highly complex
174 class hierarchy, etc. We call this mechanism generally ``inference`` throughout the
175 project.
176
177 An inference tip (or ``brain tip`` as another alias we might use), is a normal
178 transform that's only called when we try to infer a particular node.
179
180 Say for instance you want to infer the result of a particular function call. Here's
181 a way you'd setup an inference tip. As seen, you need to wrap the transform
182 with ``inference_tip``. Also it should receive an optional parameter ``context``,
183 which is the inference context that will be used for that particular block of inference,
184 and it is supposed to return an iterator::
185
186 def infer_my_custom_call(call_node, context=None):
187 # Do some transformation here
188 return iter((new_node, ))
189
190
191 MANAGER.register_transform(
192 nodes.Call,
193 inference_tip(infer_my_custom_call),
194 _looks_like_my_custom_call,
195 )
196
197 This transform is now going to be triggered whenever **astroid** figures out
198 a node for which the transform pattern should apply.
199
200
201 Module extender transforms
202 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
203
204 Another form of transforms is the module extender transform. This one
205 can be used to partially alter a module without going through the intricacies
206 of writing a transform that operates on AST nodes.
207
208 The module extender transform will add new nodes provided by the transform
209 function to the module that we want to extend.
210
211 To register a module extender transform, use the ``astroid.register_module_extender``
212 method. You'll need to pass a manager instance, the fully qualified name of the
213 module you want to extend and a transform function. The transform function
214 should not receive any parameters and it is expected to return an instance
215 of ``astroid.Module``.
216
217 Here's an example that might be useful::
218
219 def my_custom_module():
220 return astroid.parse('''
221 class SomeClass:
222 ...
223 class SomeOtherClass:
224 ...
225 ''')
226
227 register_module_extender(astroid.MANAGER, 'mymodule', my_custom_module)
228
229
230 Failed import hooks
231 ^^^^^^^^^^^^^^^^^^^^
232
233 If you want to control the behaviour of astroid when it cannot import
234 some import, you can use ``MANAGER.register_failed_import_hook`` to register
235 a transform that's called whenever an import failed.
236
237 The transform receives the module name that failed and it is expected to
238 return an instance of :class:`~astroid.nodes.Module`, otherwise it must raise
239 ``AstroidBuildingError``, as seen in the following example::
240
241 def failed_custom_import(modname):
242 if modname != 'my_custom_module':
243 # Don't know about this module
244 raise AstroidBuildingError(modname=modname)
245 return astroid.parse('''
246 class ThisIsAFakeClass:
247 pass
248 ''')
249
250 MANAGER.register_failed_import_hook(failed_custom_import)