-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathparseVariables.py
More file actions
40 lines (32 loc) · 1.23 KB
/
parseVariables.py
File metadata and controls
40 lines (32 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import ast
class variableParser:
def parse(self, file_path):
variable_dict = {}
with open(file_path, 'r') as module_file:
module_code = module_file.read()
module_ast = ast.parse(module_code)
for node in ast.walk(module_ast):
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
variable_name = target.id
variable_value = self.parse_constant(node.value)
variable_dict[variable_name] = variable_value
return variable_dict
def parse_constant(self, node):
try:
return ast.literal_eval(node)
except (SyntaxError, ValueError):
return None
@staticmethod
def restoreOriginalType(input_dict):
converted_dict = {}
for key, value in input_dict.items():
converted_value = value
if isinstance(value, str):
try:
converted_value = ast.literal_eval(value)
except (SyntaxError, ValueError):
pass
converted_dict[key] = converted_value
return converted_dict