msiemens / tinydb

TinyDB is a lightweight document oriented database optimized for your happiness :)
https://tinydb.readthedocs.org
MIT License
6.76k stars 534 forks source link

Can't use lists/dicts as arguments to `Query.test` #517

Open msiemens opened 1 year ago

msiemens commented 1 year ago

Discussed in https://github.com/msiemens/tinydb/discussions/514

Originally posted by **tgkuus** February 20, 2023 In the read the docs section Advanced queries>Custom test with parameters: I noticed I can't have the arguments in the test function be lists or dicts. Is that by design or a bug? Example of the issue. Note that the first error is at line 30. After the code is the error traceback I got. ``` from tinydb import TinyDB, Query def test_function(val,arg1,arg2): if '0' == list(val.keys())[0]: return True else: return False #make the db and add some data x = TinyDB('questions.json') x.truncate() #reset for testing some_fake_data = [{'data':{xidx:xval}} for xidx,xval in enumerate(reversed(range(100)))] print('1\n\t',some_fake_data) x.insert_multiple(some_fake_data) print('2\n\t',x.all()) #search normal - WORKS! the_return = x.search(Query().data == {'0': 99}) print('3\n\t',the_return) #search normal with test function args int and string - WORKS! arg1=0 arg2='asd' q=Query() the_return = x.search(q.data.test(test_function,arg1,arg2)) print('4\n\t',the_return) #search normal with test function args list and int - DOES NOT WORK arg1=[0,1,2,3] arg2=1 the_return = x.search(q.data.test(test_function,arg1,arg2)) print('5\n\t',the_return) #search normal with test function args int and dict - DOES NOT WORK arg1=1 arg2={'asd':1} the_return = x.search(q.data.test(test_function,arg1,arg2)) print('6\n\t',the_return) ''' Error Recieved Traceback (most recent call last): File "...", line 31, in the_return = x.search(q.data.test(test_function,arg1,arg2)) File "...", line 245, in search cached_results = self._query_cache.get(cond) File "...", line 91, in get value = self.cache.get(key) File "...", line 98, in __hash__ return hash(self._hash) TypeError: unhashable type: 'dict' ''' ```