0

This happened while using sqlalchemy .

I used kwargs to get a list from def in python. append to the list in def. You didn't even assign any parameters to the list when calling def. During the call, additional values are added to the list as duplicates.

Below is an example. What is the cause of the phenomenon?

def test(a=None, b=None, c=None, filter_list=[]):
    if a is not None:
       filter_list.append(a == model.a)
    if b is not None:
       filter_list.append(b == model.b)
    if c is not None:
       filter_list.append(c == model.c)
    query = db.session.query(model).filter(and_(*filter_list))

test(a='a', b='b', c='c')
## query value prediction > select * from model where a = %s and b = %s and c = %s
## query value result > select * from model where a = %s and b = %s and c = %s and a = %s and b = %s and c = %s and a = %s and b = %s and c = %s and a = %s and b = %s and c = %s
hangillw
  • 3
  • 3
  • 3
    If you're calling `test` multiple times, see [here](https://stackoverflow.com/questions/1367883/methods-default-parameter-values-are-evaluated-once). Don't have mutable default arguments (`=[]`), and if you do, don't mutate them (`append`). – Carcigenicate Feb 07 '22 at 14:45
  • 1
    https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – matszwecja Feb 07 '22 at 14:48

0 Answers0