'Write config.py dynamically
I have to write a config file based on the parameters given by a user.
The goal is to obtain something like that in the target file :
PrimerGCRange = namedtuple("GCRange", "min max opt")
PRIMER_SIZE_RANGES = {
"DEFAULT": PrimerSizeRange(25, 35, 30),
"HIGH_GC": PrimerSizeRange(25, 35, 30),
}
How can I have that without the lines becoming :
PRIMER_SIZE_RANGES = {"DEFAULT": [25, 35, 30], "HIGH_GC": [25, 35, 30]}
The idea is to have a dictionary where {"PRIMER_SIZE_RANGE" : "DEFAULT": PrimerSizeRange(25, 35, 30), ..}, with 25, 35, 30 the inputs of the user, is put in form by a function. Then I write this in a new file but I don't want the PrimerSizeRange to be evaluating as the destination file is a config.py.
Otherwise the namedtuple can't be used properly in others files.
Here I transform the dictionary to text
for v in values:
text += v + ' = ' + json.dumps(values[v]) + '\n'
with open(file_name, 'w') as f:
f.write(textwrap.dedent(text))
where values would be something like :
values = {
"PRIMER_SIZE_RANGES": {
"DEFAULT": PrimerSizeRange(25, 35, 30),
"HIGH_GC": PrimerSizeRange(25, 35, 30),
},
"PREFIX" : "scheme",
"OUTPUT_PATH" : "./output",
"MAX_ALN_GAP_PERCENT" : 0.03,
"MAX_REFERENCES" : 200
}
And the expected config.py :
PrimerSizeRange = namedtuple("PrimerSizeRange", "min max opt")
PRIMER_SIZE_RANGES = {
"DEFAULT": PrimerSizeRange(25, 35, 30),
"HIGH_GC": PrimerSizeRange(25, 35, 30),
}
PREFIX = "scheme"
OUTPUT_PATH = "./output"
MAX_ALN_GAP_PERCENT = 0.03
MAX_REFERENCES = 200
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
