0

I am using python library tinydb to store data.

According to tinydb documentation, the proper syntax for an example query is:

User = Query()
db.search(User.birthday.year == 1990)

Why don't we need:

User = Query()
db.search(lambda User: User.birthday.year == 1990)

db.search is a function that is only called once. This means that the function is receiving a fixed value (the result of a comparison) as an input, not a function to serve as a comparator?

How does the tinydb library achieve this weird syntax?

Jagoda Gorus
  • 329
  • 4
  • 18
Michael Sohnen
  • 953
  • 7
  • 15

1 Answers1

4

User.birthday.year isn't really an int; it's an object that represents a query to retrieve an int. The type of this object likewise defines __eq__ to return not a Boolean value, but a function that will return the result of comparing the fetched int to 1990.


Digging into the code confirms this.

Query.__getattr__ returns a new Query object, so User.birthday.year is also a Query.

The definitions of Query.__eq__ and Query._generate_test confirm that == also builds a new query.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • So are you saying that the way it achieves this is by using \_\_eq\_\_ dunder magic to (essentially) override/overload the "==" operator? – Michael Sohnen Mar 20 '19 at 14:20
  • Not just essentially; `__eq__` *defines* what `==` means for all types. If you don't override it, you inherit its definition from a parent class, which often means going back to `object.__eq__`, which simply checks for object identity. – chepner Mar 20 '19 at 14:22