In my app (
http://reeborg.ca/reeborg.html) I use Brython to enable writing programs in Python to control a virtual robot. Users can also write programs in Javascript to do the same.
When using Python, I need to make some definitions available to the users prior to executing their programs; I do this via something like
def compile_program(src):
my_globals = {}
my_globals.update(globals()) # ensure that Python builtins are available
exec("from my_module import *", my_globals)
exec(user_program, my_globals)
A while ago, I found out that switching programming mode randomly from programming in Javascript to Python and back, which the users are allowed to do, could result in errors. A solution to this problem was the following:
def compile_program(src):
if 'my_module' in sys.modules:
del sys.modules['my_module'] # forces a fresh import
my_globals = {}
my_globals.update(globals())
exec("from my_module import *", my_globals)
exec(user_program, my_globals)
The problem is that, this is slow: running my integration test suite is now annoyingly long. Furthermore, the server is being asked to do a lot more work since there is a fresh request each time.
I have tried to do the following to try to cache the result of the import
MY_MODULE = {}
exec("from my_module import *", MY_MODULE)
def compile_program(src):
my_globals = {}
my_globals.update(globals())
my_globals.update(MY_MODULE)
exec(user_program, my_globals)
However, this resulted in the same errors as if I let Brython do its own caching.
I did try to also add
if 'MY_MODULE' in my_globals:
del my_globals['MY_MODULE']
prior to doing
my_globals.update(MY_MODULE)
but that did not work.
Does anyone have any suggestion for getting Brython to simulate the result of doing a fresh import, but without actually doing an Ajax call to import a module each time?
André
P.S. I'm currently running an older version of Brython (__BRYTHON__.__MAGIC__ == "3.2.7"). If a proposed solution requires a more recent version, I will upgrade.