diff --git a/notebooks/shared/bookutils/__init__.py b/notebooks/shared/bookutils/__init__.py index 1d5d489e..4d3d1c30 100644 --- a/notebooks/shared/bookutils/__init__.py +++ b/notebooks/shared/bookutils/__init__.py @@ -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: