Search code examples
pythonpeewee

How does peewee's get method knows how to generate where clause?


Python's peewee orm library allows me to query database using the get method like this:

grandma = Person.get(Person.name == 'Grandma L.')

This query will filter the resultset based on Person's name doing a sql where behind the scenes.

I know the expression Person.name == 'Grandma L.' is evaluated first and the get method receives just a boolean value.

How does the get method inspect it's arguments to detect that the filter needs to be applyed to the 'name' field ?

PS: I read peewee's source but couldn't have any clue how it does that.


Solution

  • I know the expression Person.name == 'Grandma L.' is evaluated first and the get method receives just a boolean value.

    I don't know Peewee specifically but I do know how this sort of thing is done.

    Basically, the second part of your sentence isn't true. name is of a custom type. Its __eq__ method doesn't return just a Boolean value, but rather an object that contains information on what comparison was actually done. (This class might even derived from bool so it works like a Boolean in other contexts.) Its other rich comparison methods are similar.

    But how does Person.name know that its name is name? The answer to that is that Person probably doesn't actually have a name attribute. Instead, it has a __getattr__() method that returns the name object, which is the custom class that has the __eq__ method I just described.

    Since Person.__getattr__() receives the name of the attribute, it can bake that name into the value it returns for name. Then the custom __eq__ method on name returns a Boolean-like object that contains some representation of name == 'Grandma L.' inside it. And Person.get() uses this representation to put together the query.