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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So are you saying that the way it achieves this is by using __eq__ dunder magic to (essentially) override/overload the "==" operator?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.