I'm trying to read and edit a config file in python. Here is the file structure:
main.py
folder
-> __init__.py
-> module.py
-> config.py
I have four files:
main.py
import folder.config as config
import folder.module as module
if __name__ == "__main__":
config.x = 2
module.foo()
init.py
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
module.py
import config
def foo():
print("Result from function: " str(config.x))
config.py
x = 10
I expect the result from calling 'foo' to be '2', but instead it prints '10', the config file's default value. How can I ensure that changes made to 'config.py' in 'main.py' persist to other modules?
Any help would be greatly appreciated!
CodePudding user response:
Why don't you use JSON or csv or any other format to store values?
EDIT: I suggest following solution:
main.py
import folder.config as config
import folder.module as module
if __name__ == "__main__":
config.set_x(2)
module.foo()
init.py
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
module.py
import config
def foo(): print(f"Result from function: { str(config.get_x()) }")
config.py
import json
def read_json():
with open("data.json") as f: d = json.load(f)
return d
def write_json(d):
with open('data.json', 'w') as f: json.dump(d, f)
try:
data = read_json()
except:
data = {}
write_json({})
def set_x(val):
data["x"] = val
write_json(data)
def get_x():
print(data)
return data["x"]