Search code examples
pythonmagic-methods

How and where to use Python's __and__, __or__, __invert__ magic methods properly


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


Solution

  • 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: