Skip to content

Commit

Permalink
Update from debuggingbook
Browse files Browse the repository at this point in the history
  • Loading branch information
andreas-zeller committed Jan 5, 2025
1 parent c4d2345 commit 1e453d2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 32 deletions.
33 changes: 3 additions & 30 deletions notebooks/shared/bookutils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,37 +164,10 @@ def show_ast(tree: AST) -> Optional[Any]:
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()
# Note: For Python >=3.12, this needs a patched `showast` module
# e.g. git+https://github.com/andreas-zeller/show_ast.git@andreas
import showast
from showast.rendering.graphviz import render
return render(tree, showast.Settings)

# Allow importing the showast module
def import_showast() -> None:
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')

return showast.show_ast(tree)

# Escaping unicode characters into ASCII for user-facing strings
def unicode_escape(s: str, error: str = 'backslashreplace') -> str:
Expand Down
24 changes: 22 additions & 2 deletions notebooks/shared/ipypublish/scripts/export_plugins.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,31 @@
import glob
import imp
import inspect
import logging
import os
import uuid
import warnings


# Replacement for imp.load_source; see https://docs.python.org/3/whatsnew/3.12.html#imp
import importlib.util
import importlib.machinery

def load_source(modname, filename):
loader = importlib.machinery.SourceFileLoader(modname, filename)
spec = importlib.util.spec_from_file_location(modname, filename, loader=loader)
module = importlib.util.module_from_spec(spec)
# The module is always executed and not cached in sys.modules.
# Uncomment the following line to cache the module.
# sys.modules[module.__name__] = module
loader.exec_module(module)
return module

# Alternative if the above code does not work
# import imp
# load_source = imp.load_source



# py 2/3 compatibility
try:
import pathlib
Expand All @@ -22,7 +42,7 @@ def load_source(modname, fname):
loader.exec_module(mod)
return mod
except ImportError as err:
load_source = lambda modname, fname: imp.load_source(modname, fname)
load_source = lambda modname, fname: load_source(modname, fname)

from ipypublish import export_plugins

Expand Down

0 comments on commit 1e453d2

Please sign in to comment.