user5281291
user5281291

Reputation:

Storing application settings in Python

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?

Upvotes: 2

Views: 3143

Answers (3)

Mahmoud Elshahat
Mahmoud Elshahat

Reputation: 1959

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)

Upvotes: 0

Semih Yagcioglu
Semih Yagcioglu

Reputation: 4101

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

Upvotes: 0

nigel222
nigel222

Reputation: 8192

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.

Upvotes: 1

Related Questions