Best practice for lazy loading Python modules

后端 未结 4 1372
孤城傲影
孤城傲影 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条回答
  •  梦毁少年i
    2021-02-03 19:50

    Nice pattern from sqlalchemy: dependency injection:

    @util.dependencies("sqlalchemy.orm.query")
    def merge_result(query, *args):
        #...
        query.Query(...)
    

    Instead of declaring all "import" statements at the top of the module, it will only import a module when it's actually needed by a function. This can resolve circular dependency problems.

提交回复
热议问题