2

I am looking for a smart way to store my settings in Python. All I want to do is to set some parameters and use it in the code.

I found this Best practices for storing settings and this Storing application settings in C# but I don't think that helps me to solve my problem. I want store some parameters for example age weight and name etc. and access them easily.

Is there any best practice?

Community
  • 1
  • 1

3 Answers3

1

If you like windows .ini file format, Python comes with ConfigParser (python3 configparser) to interpret them. The doc makes this look more complicated than it is - skip to the end for a simple example.

You can also use (abuse?) import, to load a settings.py file.

Putting your parameters in a class is good. You can add load and save methods to read / overrride defaults from a config file (if it exists) and to create/update a config file using the current values.

nigel222
  • 7,582
  • 1
  • 14
  • 22
0

I think one way to do that is to store your parameters in a class.

Like this:

class Settings:

    # default settings
    name = 'John'
    surname = 'Doe'
    age = 45
    gender = 'Male'

Another way is to store these variables in a configuration file and then read from it. But I find the former a lot more easier because you can access in your code easier.

Like this:

from settings import *
settings = Settings()
username = settings.name
Semih Yagcioglu
  • 4,011
  • 1
  • 26
  • 43
  • I believe the second line of your usage example should be `username = Settings.name`. Also, there's no reason for the `__init__()` method because it's never used (even if it did something). – martineau Aug 30 '15 at 09:41
  • I took that from a working example but missed that line. Thanks for pointing out! – Semih Yagcioglu Aug 30 '15 at 09:50
0

Pickle it, you can store any python data structure in file and load it later

import pickle
data = dict(user='Homer', age=45, brain=None)

#save data to file
with open('setting.cfg', 'wb') as f: 
            pickle.dump(data, f)

#load data from file
with open('setting.cfg', 'rb') as f: 
            data = pickle.load(f)
Mahmoud Elshahat
  • 1,873
  • 10
  • 24