I faced this really weird issues with library imports in python.
Essentaily, consider the following program
So test in run in a different process than this main process. Because we are using spawn
mode, there will be a new interpreter.
Spawn
Start MethodWhen using the
spawn
start method in Python’s multiprocessing module, each new process starts a fresh Python interpreter. This means that each process has its own separate memory space, including its own separate imports.
When new process is started, the new interpreter will import the main module of the program (i.e., the script that was initially run). This means that any top-level code in the main module will be executed, including any import statements.
So these, because they are global imports, are carried over to the new process.
I know that pango fails because the import is global. We cannot allow a global level import.
We can do the import inside the function, to no longer get errors.
On the other hand, the visualization.PangoVisualizer
module will only be imported in the test
function, because this import statement is inside a function and is therefore not at the top level of the main module. This means that the PangoVisualizer
module will only be imported in the process that runs the test
function, and not in the process that runs the test2
function.