Search code examples
python-3.xglobal-variablesfile-manipulationconfiguration-files

How to make a config file that stores global variables but can also be easily edited from the level of the code?


I have a Python project that uses some global variables. The project has multiple .py files and all of them need to be able to read those variables easily. All of them should also be able to edit them.

Right now I am using a .py file that stores the variables and I simply import them in other files as a module. This solution is far from optimal, though, because I can't edit them easily. I naively tried to write setters for the variables, but obviously that doesn't work either.

I thought about using JSON for the variables, but then reading them wouldn't be as easy as 'import cfg'.

Is there a standard solution for this problem that I'm not aware of because I'm a noob?

Thanks for every answer.


Solution

  • Store information in a CSV and then use csv.reader to write the key, value pairs to something like a dictionary. Here's some example code to get you started:

    csv file:

    firstname Garrett
    something_else blah
    

    Python:

    import csv
    
    output = []
    with open('csv.csv') as csvfile:
        reader = csv.reader(csvfile, delimiter=' ')
        for row in reader:
            output.append(tuple(row))
    return {key: value for (key, value) in output}