I faced this really weird issues with library imports in python.

Essentaily, consider the following program

import multiprocessing as mp
import numpy as np
import pyzed.sl as sl
 
def test():
    from visualization import PangoVisualizer
    vis = PangoVisualizer()
    while True:
        vis.update([], [], [])
 
def test2():
    print("hello")
 
if __name__ == "__main__":
    mp.set_start_method("spawn", force=True)
 
    a = mp.Process(target=test)
    b = mp.Process(target=test2)
 
    a.start()
    b.start()
    a.join()
    b.join()
 

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 Method

When 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.

import multiprocessing as mp
import numpy as np
 
def test():
    from visualization import PangoVisualizer
    vis = PangoVisualizer()
    while True:
        vis.update([], [], [])
 
def test2():
    import pyzed.sl as sl
    print("hello")
 
if __name__ == "__main__":
    mp.set_start_method("spawn", force=True)
 
    a = mp.Process(target=test)
    b = mp.Process(target=test2)
 
    a.start()
    b.start()
    a.join()
    b.join()
 

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.