Similar unanswered question: Python AST – How to see value of assign node?
I am trying to obtain the assignments statements in a file. Example:
JavaScript
x
7
1
def isMaskedArray(x):
2
isarray = isMaskedArray
3
masked_array = MaskedArray
4
5
_ShapeType = TypeVar("_ShapeType", bound=Any)
6
7
JavaScript
1
56
56
1
Module(
2
body=[
3
FunctionDef(
4
name='isMaskedArray',
5
args=arguments(
6
posonlyargs=[],
7
args=[arg(
8
arg='x',
9
annotation=None,
10
type_comment=None)],
11
vararg=None,
12
kwonlyargs=[],
13
kw_defaults=[],
14
kwarg=None,
15
defaults=[]),
16
body=[Expr(value=Constant(
17
value=Ellipsis,
18
kind=None))],
19
decorator_list=[],
20
returns=None,
21
type_comment=None),
22
Assign(
23
targets=[Name(
24
id='isarray',
25
ctx=Store())],
26
value=Name(
27
id='isMaskedArray',
28
ctx=Load()),
29
type_comment=None),
30
Assign(
31
targets=[Name(
32
id='masked_array',
33
ctx=Store())],
34
value=Name(
35
id='MaskedArray',
36
ctx=Load()),
37
type_comment=None),
38
Assign(
39
targets=[Name(
40
id='_ShapeType',
41
ctx=Store())],
42
value=Call(
43
func=Name(
44
id='TypeVar',
45
ctx=Load()),
46
args=[Constant(
47
value='_ShapeType',
48
kind=None)],
49
keywords=[keyword(
50
arg='bound',
51
value=Name(
52
id='Any',
53
ctx=Load()))]),
54
type_comment=None)],
55
type_ignores=[])
56
and form them into a dictionary like so:
JavaScript
1
2
1
[{isarray: isMaskedArray}, {masked_array: MaskedArray}]
2
I only want the Assigns with value and target, no call objects. The AST module is very difficult to understand and I would appreciate any help.
Advertisement
Answer
You can use ast.walk
. This will recursively yield all descendant nodes. You can then check if the node is an instance of ast.Assign
, if yes, it has targets
and value
attributes which contains the details you are looking for.
JavaScript
1
13
13
1
>>> import ast
2
>>>
3
>>> tree = ast.parse(source)
4
>>>
5
>>> result = {
6
node.targets[0].id: node.value.id
7
for node in ast.walk(tree)
8
if isinstance(node, ast.Assign)
9
}
10
>>>
11
>>> print(result)
12
{'isarray': 'isMaskedArray', 'masked_array': 'MaskedArray'}
13