BUG: sys.modules['__main__'] not pointing __import__('__main__')
cpython automatically gives access to sys.modules[__name__] from module '__main__' and returns value of __import__('__main__').
micropython does not and forces to use__import__(__name__) which is not a good way to get a module by fully qualified name ( eg when getting a dot package name you only get toplevel ).
Circular Import
OK say I have main.py and another module called test
There is a single function inside of the test module. Inside that function I import 2 variables from main. The test module gets imported into main and other things run setting the variables and whatever else and the very last thing that gets done if that function inside of the test module gets run.
What is happening is the code inside of main.py is getting run a second time when those 2 variables get imported. Those variables are dedicated way at the top of the main.py file.
In CPython I am able to do this without an issue so I am not sure where the problem stems from. In CPython if a module level variable is declared after a class is that uses that variable and an import gets done of only the class when the code runs that is in the class there will be a name error for that module level variable. That is because as soon as the code for the class loads the import mechanism does it's thing any any other code in that module never gets run.
I know the code is being run 2 times because I have allocated a block of DMA memory the first go around and I check to make sure the memory was allocated and I print out a message letting me know it is. If the memory is not allocated I raise an exception. Well I get the message printed out that it is successful and then after more code loads I get the exception for it not being allocated.
I would imagine this is a bug because the code inside of a module that has already been imported should not run more than a single time if it is imported a second time.
I believe I know where the issue is...
I am running my code on an ESP32-WROVER-B
in main.c in the esp32 port you have this code.
pyexec_frozen_module("_boot.py");
pyexec_file_if_exists("boot.py");
if (pyexec_mode_kind == PYEXEC_MODE_FRIENDLY_REPL) {
int ret = pyexec_file_if_exists("main.py");
if (ret & PYEXEC_FORCED_EXIT) {
goto soft_reset_exit;
}
}
Does the pyexec_file_if_exists function utilize the same mechanics as import main or does it use the mechanics of exec where the code is read and run and not imported. This is the only thing I can imagine that would cause that issue. This is because the interpreter has no knowledge of the code in the main.py file being run so when I import the main.py code it gets ran a second time. Plausible? How to correct the issue is beyond me. IDK is the __name__ == '__main__' hold true in Micropython like it does in CPython. An imported module that is being imported for the first time I would imagine it would not have '__main__' as it's name.