-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode2_python_full_example.py
More file actions
40 lines (31 loc) · 992 Bytes
/
code2_python_full_example.py
File metadata and controls
40 lines (31 loc) · 992 Bytes
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 ASTConvertStrToCall(ast.NodeTransformer):
"""Transform 's' into contains(title, 's')"""
def visit_Str(self, node):
return ast.copy_location(
ast.Call(
func=ast.Name(id='contains', ctx=ast.Load()),
args=[ast.Str(node.s)],
keywords=[]
),
node
)
def dsl_to_func(code_str):
"""
Convert string into python function
"""
parsed = ast.parse(code_str, '<rule>', 'eval')
tree = ASTConvertStrToCall().visit(parsed)
ast.fix_missing_locations(tree)
compiled = compile(tree, "<rule>", "eval")
def func(title):
namespace = {
'contains': lambda kw: kw in title
}
return eval(compiled, namespace)
return func
if __name__ == '__main__':
dsl_str = '"python" and ("developer" or "programmer")'
pyfunc = dsl_to_func(dsl_str)
print(pyfunc('python developer'))
print(pyfunc('java developer'))