2
votes

I wrote this loop to dynamically build a select statement using Sqlalchemy in an attempt to have less DB hits.

I don't understand why I'm getting a Maximum recursion depth exceeded Error when query.all() is called.

When I change the recursion depth max to 2000 this query works fine.

Code:

filter_cond = False
for asset in assets:
    filter_cond = or_(filter_cond, and_(model.version == asset.get("version"),
                                        model.id == asset.get("id"),
                                        model.account_id == account_id))
query = session.query(model).filter(filter_cond)
result_set = query.all()
1

1 Answers

3
votes

currently you're building the following nested logic condition recursively in the for loop

or(...or(or(false, condition1), condition2), ... conditionN)

instead, if you express the equivalent condition:

or(condition1, condition2, ... conditionN)

using a list comprehension & unpacking, recursion is avoided.

def condition(model, asset):
    return and_(model.version == asset.get("version"),
                model.id == asset.get("id"),
                model.account_id == account_id)

filter_cond = or_(*[condition(model, asset) for asset in assets])