-
Notifications
You must be signed in to change notification settings - Fork 5
/
compiler_ipython.py
46 lines (30 loc) · 1.37 KB
/
compiler_ipython.py
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
41
42
43
44
45
# coding: utf-8
# # The IPython compiler
# In[2]:
from nbconvert.exporters.python import PythonExporter
from IPython.core.compilerop import CachingCompiler
import ast
class Compiler(CachingCompiler):
"""{Shell} provides the IPython machinery to objects."""
@property
def ip(Compiler):
"""The current interactive shell"""
from IPython import get_ipython
from IPython.core.interactiveshell import InteractiveShell
return get_ipython() or InteractiveShell()
def ast_transform(Compiler, node):
for visitor in Compiler.ip.ast_transformers:
node = visitor.visit(node)
return node
@property
def transform(Compiler): return Compiler.ip.input_transformer_manager.transform_cell
def compile(Compiler, ast):
"""Compile AST to bytecode using the an IPython compiler."""
return (Compiler.ip and Compiler.ip.compile or CachingCompiler())(ast, Compiler.filename, 'exec')
def ast_parse(Compiler, source, filename='<unknown>', symbol='exec', lineno=0):
return ast.increment_lineno(super().ast_parse(source, Compiler.filename, 'exec'), lineno)
# In[4]:
if __name__ == '__main__':
from pathlib import Path
Path('../importnb/compiler_ipython.py').write_text(PythonExporter().from_filename('compiler_ipython.ipynb')[0])
__import__('doctest').testmod()