How to avoid computation every time a python module is reloaded

后端 未结 13 736
温柔的废话
温柔的废话 2021-02-06 10:55

I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the mod

13条回答
  •  醉话见心
    2021-02-06 11:36

    Calculate your global var on the first use.

    class Proxy:
        @property
        def global_name(self):
            # calculate your global var here, enable cache if needed
            ...
    
    _proxy_object = Proxy()
    GLOBAL_NAME = _proxy_object.global_name
    

    Or better yet, access necessery data via special data object.

    class Data:
        GLOBAL_NAME = property(...)
    
    data = Data()
    

    Example:

    from some_module import data
    
    print(data.GLOBAL_NAME)
    

    See Django settings.

提交回复
热议问题