I am working on some software that queries a database. In particular, if you query the database with a certain parameter, it won't find a matching value, so you should query it again with a different parameter.
Below is a short script that outlines the problem. query_db is just a dummy function intended to mimic the behaviour of a query to a database containing an entry indexed by 1. In the get_db_params function, I query the db using the a parameter. If it returns None, then I try again with the b parameter. If that also returns None, then get_db_params throws an error.
Calling get_db_params with d1 and d2 as arguments returns "some_value", while d3 raises a KeyError.
My question is: this does not seem very pythonic, especially having two if params is None: in a row. Any advice on how to improve these functions?
def query_db(x):
if x == 1:
return "some_value"
else:
return None
def get_params(d):
params = query_db(d['a'])
if params is None:
params = query_db(d['b'])
if params is None:
raise KeyError("Params not found in db")
return params
d1 = {'a': 1, 'b': 1}
d2 = {'a': 0, 'b': 1}
d3 = {'a': 0, 'b': 0}
params = get_params(d1)
params = get_params(d2)
params = get_params(d3)