Why does a python module act like a singleton?

前端 未结 2 969
说谎
说谎 2020-12-03 08:21

I create a dictionary from a remote database as part of my application run. This process is pretty I/O heavy, so I\'ve decided to create a \"singleton\" instance of this di

2条回答
  •  囚心锁ツ
    2020-12-03 09:13

    This is the Python Language Reference's description of how importing a module works:

    (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace

    (Emphasis added.) Here, initializing a module means executing its code. This execution is only performed if necessary, i.e. if the module was not previously imported in the current process. Since Python modules are first-class runtime objects, they effectively become singletons, initialized at the time of first import.

    Note that this means that there's no need for a get_state_dict_code function; just initialize state_code_dict at top-level:

    state_code_dict = generate_state_code_dict()
    

    For a more in-depth explanation, see this talk by Thomas Wouters, esp. the first part — around 04:20 — where he discusses the "everything is runtime" principle.

提交回复
热议问题