Python 中的异步导入

Asynchronous import in Python

我需要导入一些大型且计算量大的东西,但我的应用程序中不需要它。有没有办法在 python 中异步导入某些内容,即当我的脚本是 运行 时,无论导入需要在后台完成什么? Google 到目前为止没有帮助。

您可以在不同的线程中将 python 导入器作为函数调用,而不是使用 import foo。由于此导入在计算上很昂贵,并且 python 一次只允许一个线程 运行 (除非它像 pandas 那样释放 GIL),您可能会发现没什么好处。不过,

import threading
import time

def begin_load_foo():
    global foo_thread
    foo_thread = threading.Thread(target=load_foo_thread)
    foo_thread.start()

def load_foo_thread():
    global foo
    print("start importing")
    foo = __import__('foo')
    print("done importing")

def wait_foo():
    print('wait')
    foo_thread.join()
    print('done')

def do_other_things():
    time.sleep(1)

begin_load_foo()
do_other_things()
wait_foo()
foo.bar()