0
\$\begingroup\$

I have json data in a file and I want to load the file content only once when application is initiated instead of calling the loading file multiple times in class instances.

I created a config which loads on app init named REPOSITORY_CONFIG.

Then created a script with the method like this:

import json

CACHE = None

def get_repo_config():
    global CACHE
    with open('config.json') as config_json:
        CACHE = json.load(config_json)
    return CACHE

I have config.py

REPOSITORY_CONFIG = CACHE if CACHE else get_repo_config

This config is used in a class method like this:

import REPOSITORY_CONFIG

class Test():

  def check_config():
    config_data = REPOSITORY_CONFIG

Is there any other way to do this or I am not following right approach?

\$\endgroup\$
1
  • 2
    \$\begingroup\$ It looks like REPOSITORY_CONFIG is a dict, so import REPOSITORY_CONFIG doesn't make sense. Is it supposed to be import config and then config_data = config.REPOSITORY_CONFIG? \$\endgroup\$
    – RootTwo
    Commented Nov 16, 2022 at 0:10

1 Answer 1

1
\$\begingroup\$

Module level code is only executed the first time a module is imported. Subsequent imports return the already imported module without rerunning the module level code. So use top level code to load the json file. Something like:

# config.py

# this module level code only gets run the first time the module is
# imported.
with open('config.json') as config_json:
    REPOSITORY_CONFIG = json.load(config_json)

# ... other config stuff ...

Then it can be used like:

import config

class Test():

    def check_config():
        config_data = config.REPOSITORY_CONFIG
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.