Best practice for lazy loading Python modules

后端 未结 4 1371
孤城傲影
孤城傲影 2021-02-03 19:09

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 cum

4条回答
  •  悲&欢浪女
    2021-02-03 19:46

    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.

    The difference between your code and

    def render_with_jinja2(self, values, template_name):
        import jinja2
        env = jinja2.Environment(...)
    

    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.

提交回复
热议问题