What's the best way to read a condition from a config file in Python using ConfigParser
and json
? I want to read something like:
[mysettings]
x >= 10
y < 5
and then apply it to code where x
and y
are defined variables, and the condition will be applied as to the values of x, y
in the code. Something like:
l = get_lambda(settings["mysettings"][0])
if l(x):
# do something
pass
l2 = get_lambda(settings["mysettings"][1])
if l2(y):
# do something
pass
ideally I'd like to specify conditions like x + y >= 6
too.
there must be a better way, but the idea is to constrain the values of variables using simple boolean expressions from the config file.
I don't think you want—or need—to use both
configparser
andjson
, as both are sufficient by itself. Here's how to do it with each one:Say you had a config file from a trusted source that contained something like this:
myconfig.ini
It could parsed and used like this:
Which would result in the following output:
If the information the was instead kept in a JSON-format file similar to this:
myconfig.json
It could be easily parsed with the
json
module and used in a similar fashion:...the remainder would be the identical and produce the same results. i.e.:
This is an example using Python itself as the language for describing the config file:
config.py
main.py
Output:
This of course assumes that the config file is considered trusted input, because by doing
condition(value)
you'll execute whatever function is defined in the config file.But I don't see any way around that, regardless of what language you're using: conditions are expressions and therefore executable code. If you want to end up with a Python expression that you can just use in your code, you'll have to evaluate that expression sooner or later.
Edit:
If for some reason you really can't use Python, this is how you could do it with a config file in JSON:
config.json
main.py
Result:
Or, closer to your example:
Result: