1

I was googling around to find any use cases or examples of these methods but could not find any detailed explanation, they are just listed along other similar methods. Actually, I was looking through some code on github and came across these methods but could not understand the usage. Can somebody please provide a detailed explanation of these methods. This is the link of github code where I came across them: https://github.com/msiemens/tinydb/blob/master/tinydb/queries.py

Humoyun Ahmad
  • 2,875
  • 4
  • 28
  • 46

1 Answers1

7

The magic methods __and__, __or__ and __invert__ are used to override the operators a & b, a | b and ~a respectively. That is, if we have a class

class QueryImpl(object):
    def __and__(self, other):
        return ...

then

a = QueryImpl(...)
b = QueryImpl(...)
c = a & b

is equivalent to

a = QueryImpl(...)
b = QueryImpl(...)
c = a.__and__(b)

These methods are overridden in tinydb to support this syntax:

>>> db.find(where('field1').exists() & where('field2') == 5)
>>> db.find(where('field1').exists() | where('field2') == 5)
#                                    ^

See also:

Graham
  • 7,431
  • 18
  • 59
  • 84
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005