If all you are doing is loading some static data and not code, putting the data in json is going to be the simplest approach. However, importing python code is also doable and gives you the ability to use the full power of python in defining your user data.
Python has a library for doing this, called importlib. You can use it to import a module by path with importlib.util.spec_from_file_location
Here's an example of a helper function to use that method:
import importlib.util
import sys
def import_module_from_path(module_name, file_path):
spec = importlib.util.spec_from_file_location(module_name, file_path)
if spec is None:
raise ImportError(f"Could not find module spec for '{module_name}' at '{file_path}'")
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module # Add the module to sys.modules
spec.loader.exec_module(module)
return module
To test it out, let's assume the user's file is in /tmp/User_data/Data.py, and that it contains the following:
# Data.py
customizations = {
"one": 1,
"two": 2,
}
We can now import customizations like so:
# example.py
try:
user_data = import_module_from_path("user_data", "/tmp/User_data/Data.py")
print(f"customizations: {user_data.customizations}")
except ImportError as e:
print(f"Error importing plugin: {e}")
When you run the code you should see output like this:
$ python example.py
customizations: {'one': 1, 'two': 2}
Data.pyis a Python file that defines a Python dictionary with the user's data, is that correct? If so, your approach sounds not ideal to me. Probably, thejsonformat is what you are looking for: It is a data format that stores dictionaries in text files. Python supports it natively through itsjsonmodule: usejson.load()to read*.jsonfiles into Python dictionaries andjson.dump()to write*.jsonfiles from Python dictionaries.importlib.utildocumentation.