2323# @date May 2023
2424#
2525
26- import sys , os , types
27- from typing import Union , Dict , Callable
26+ import sys , os
27+ from typing import Union , Dict
2828import importlib
2929from importlib import machinery
30- from importlib import util
30+ import inspect
31+ import functools
3132
3233from . import pythonmonkey as pm
3334
@@ -223,7 +224,9 @@ def load(filename: str) -> Dict:
223224 require = createRequire(__file__)
224225 require('./my-javascript-module')
225226"""
226- def createRequire (filename ):
227+ # We cache the return value of createRequire to always use the same require for the same filename
228+ @functools .lru_cache (maxsize = None ) # unbounded function cache that won't remove any old values
229+ def createRequire (filename : str ):
227230 createRequireInner = pm .eval ("""'use strict';(
228231function createRequire(filename, bootstrap_broken)
229232{
@@ -245,3 +248,11 @@ def createRequire(filename):
245248 return module.require;
246249})""" )
247250 return createRequireInner (filename )
251+
252+ def require (moduleIdentifier : str ):
253+ # Retrieve the caller’s filename from the call stack
254+ filename = inspect .stack ()[1 ].filename
255+ # From the REPL, the filename is "<stdin>", which is not a valid path
256+ if not os .path .exists (filename ):
257+ filename = os .path .join (os .getcwd (), "__main__" ) # use the CWD instead
258+ return createRequire (filename )(moduleIdentifier )
0 commit comments