Skip to content

Commit

Permalink
Hack to get show_ast() running with Python 3.12
Browse files Browse the repository at this point in the history
  • Loading branch information
andreas-zeller committed Nov 9, 2024
1 parent 0d91a49 commit 52e262e
Showing 1 changed file with 34 additions and 4 deletions.
38 changes: 34 additions & 4 deletions notebooks/shared/bookutils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,14 +158,44 @@ def getsourcelines(function: Any) -> Tuple[List[str], int]:

# Showing ASTs
def show_ast(tree: AST) -> Optional[Any]:
if rich_output():
import showast # We can import showast only when in a notebook
return showast.show_ast(tree)
else:
if not rich_output():
# We can import showast only when in a notebook
import ast # Textual alternative
print(ast.dump(tree))
return None

# show_ast() no longer works in Python 3.12: the `imp` module is deprecated
# import showast
# return showast.show_ast(tree)

# Workaround, avoiding `imp`
import_showast()
import showast
from showast.rendering.graphviz import render
return render(tree, showast.Settings)

# Allow importing the showast module
def import_showast():
try:
import showast
return
except ModuleNotFoundError:
pass

# Create a local (empty) 'imp' module while importing showast
# This is an ugly hack until the `showast` module is updated to 3.12
import os, sys, shutil
os.mkdir('imp')
imp_init = os.path.join('imp', '__init__.py')
with open(imp_init, 'w') as fd:
pass
original_sys_path = sys.path
sys.path = ['.'] + sys.path
import showast
sys.path = original_sys_path
shutil.rmtree('imp')


# Escaping unicode characters into ASCII for user-facing strings
def unicode_escape(s: str, error: str = 'backslashreplace') -> str:
def ascii_chr(byte: int) -> str:
Expand Down

0 comments on commit 52e262e

Please sign in to comment.