I have a set of parameters, and I need to get the expression:
So I got this parameters:
filters = {
"type": 'human',
"age": [{'min': 4, 'max': 8}, {'min': 15, 'max': 30}],
"size": [{'min': 60}],
}
And my goal is to obtain this string from it:
type == 'human' and ((age >= 4 and age <= 8) or (age >= 15 and age <= 30)) and size >= 60
But when I am writing my script to do so, I keep having small details that bother me like the position of the 'or' or 'and' or the parenthesis.
And i think it really hit the lisibility here.
So I though maybe there was a better way, but searching google only show me the 'inverse' of what I want, that is transforming expression to expression tree.
I am trying to generate a string expression from a set of data (for a filter).
So if someone have a better idea, (or algo, or ...)
Here is my script:
#!/usr/bin/python3
# goal : type == 'human' and ((age >= 4 and age <= 8) or (age >= 15 and age <= 30)) and size >= 60
filters = {
"type": 'human',
"age": [{'min': 4, 'max': 8}, {'min': 15, 'max': 30}],
"size": [{'min': 60}],
}
s = ''
type_first = True
for key, value in filters.items():
if type_first:
type_first = False
s += "("
else:
s += " and ("
value_first = True
if(isinstance(value, str)):
s += "%s == %s" % (key, value)
elif(isinstance(value, list)):
if value_first:
value_first = False
else:
s += " and"
dict_first = True
for dict_ in value:
if dict_first:
dict_first = False
s += "("
else:
s += " and ("
if dict_.get('min', 0):
s += "%s >= %s" % (key, dict_['min'])
if dict_.get('max', 0):
s += " or "
if dict_.get('max', 0):
s += "%s <= %s" % (key, dict_['max'])
s += ")"
s += ")"
print(s)