Reputation: 10443
I working improve the quality of the scripts I write to make them more maintainable avoiding hard coding values. So far I'm using a json file to save this values, E.G.
A json file called config_test.json:
{"input_dir":"data/input",
"output_dir":"data/output",
"default_value":10,
"dtypes":["str","int","str","float"]
}
Then I read this values from the main file:
import json
with open('config_test.json') as f:
config_d = json.load(f)
config_d
default_value = config_d['default_value']
dtypes = config_d['dtypes']
input_dir = config_d['input_dir']
output_dir = config_d['output_dir']
I'm not completely comfortable with this solution, is there any standard approach to writing config files in python?
Upvotes: 1
Views: 188
Reputation: 15320
Do not discount the possibility of writing your config file in Python itself.
some_dir/app_config.py
input_dir = "data/input"
output_dir = "data/output"
default_value = 10
dtypes = "str int str float".split()
bin/app.py
import argparse
import app_config as config
parser = argparse.ArgumentParser()
parser.add_argument('--inputdir', default=config.input_dir)
Upvotes: 1
Reputation: 465
Make your life easier with pyyaml
import yaml
with open("settings.yml", 'r') as stream:
data = yaml.safe_load(stream)
Your settings.yml =>
ip_address : '0.0.0.0'
sqlite : 'sqlite:///data.db'
key : 'super-secret-hoho'
answers:
technology: ['option3', 'option3', 'option4', 'option3', 'option3', 'option4', 'option4', 'option2', 'option3', 'option3']
Then access with
my_not_hardcoded_ip = data['ip_address']
Its better to read and cleaner , i totally recommend it!
Upvotes: 1