0

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.

  • Use a database or write a file. Those two seem like the most obvious answers. – Garrett Kadillak May 08 '17 at 01:41
  • @GarrettKadillak I thought about it, but it seems excessive as I only need to store about 10 variables. I don't want to overcomplicate things. – Alicja Barankiewicz May 08 '17 at 01:42
  • I agree a database is overkill but you could use [sqlite](https://www.sqlite.org/). Also, reading/writing files with Python is incredibly easy so I wouldn't agree that it's complicating things. – Garrett Kadillak May 08 '17 at 01:46
  • @GarrettKadillak thanks for the suggestion on sqlite, I will read about it. As for the file writing - so you suggest storing just the values of those variables in a text file and then reading them and actually assigning them to the right variable names in the 'cfg.py' module? What I like about having a .py file as the config is that I don't need to mind the order of the variables, I can add comments and basically organize the file to be as readable as possible. Reading from a file through standard Python functions seems much more constrained – Alicja Barankiewicz May 08 '17 at 01:49
  • You can read a CSV as a dictionary as python with [`DictReader`](https://docs.python.org/2/library/csv.html) so you can organize the file however you want :) – Garrett Kadillak May 08 '17 at 02:03
  • @GarrettKadillak this is awesome. Thank you! – Alicja Barankiewicz May 08 '17 at 02:19
  • Just added an answer with some code to help get you started. Hope this all helps! – Garrett Kadillak May 08 '17 at 02:22

1 Answers1

0

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}
Garrett Kadillak
  • 1,026
  • 9
  • 18