延迟加载Python模块的最佳实践 [英] Best practice for lazy loading Python modules
问题描述
偶尔我想在Python中加载惰性模块。通常,因为我想保持运行时需求或启动时间低,并将代码分成子模块将是麻烦的。一个典型的用例和我目前的首选实现是:
Occasionally I want lazy module loading in Python. Usually because I want to keep runtime requirements or start-up times low and splitting the code into sub-modules would be cumbersome. A typical use case and my currently preferred implementation is this:
jinja2 = None
class Handler(...):
...
def render_with_jinja2(self, values, template_name):
global jinja2
if not jinja2:
import jinja2
env = jinja2.Environment(...)
...
有没有理由/更好的方法来实现延迟模块加载?
I wonder: is there a canonical/better way to implement lazy module loading?
推荐答案
VM维护已经导入的模块的列表,并且任何后续尝试导入该模块导致sys.modules中的快速dict查找,而没有别的。
There's no reason for you to keep track of imports manually -- the VM maintains a list of modules that have already been imported, and any subsequent attempts to import that module result in a quick dict lookup in sys.modules and nothing else.
您的代码和
def render_with_jinja2(self, values, template_name):
import jinja2
env = jinja2.Environment(...)
$ b b
为零 - 当我们点击该代码时,如果 jinja2
未导入,则会导入。如果已经存在,则继续执行。
is zero -- when we hit that code, if jinja2
hasn't been imported, it is imported then. If it already has been, execution continues on.
这篇关于延迟加载Python模块的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!