| operator has two magic methods, normal and reflected.
# object + other
__or__(self, other)
# Implements bitwise or using the | operator.
# other + object
__ror__(self, other)
# Implements reflected bitwise or using the | operator.
in operator only has one magic method.
# item in object
__contains__(self, item)
# __contains__ defines behavior for membership tests using in and not in.
How can I implement in operator reflected magic method?
# object in sequence
__rcontains__(self, sequence):
# defines behavior for self in or not in sequence
It will be useful when you want to implement sql conditions
class Field(object):
def __lt__(self, other):
return '<', self._value, other
Model.objects.filter(Field('a') > 1)
Model.objects.filter(Field('a') in [1, 2, 3, 4])
You can't, because the in operator is semantically tied to the definition of what it means for an object to "contain" another. So the operation has to be defined in the container class (here, list), not the value (Field).
To illustrate, in in your case is meant to be used like this:
Field('a') in [Field('a'), Field('b'), Field('c')]
Which of course is not what you want.
The closest you can get to what you want here is, as you mentioned in the comments, to use something like Django's fieldname__in==[1, 2, 3, 4] or SQLAlchemy's Table.fieldname.in_([1, 2, 3, 4]). For example, you could add a method to Field:
Field('a').is_in([1, 2, 3])
Another approach would be to create a specific container class so you can write:
Field('a') in Values([1, 2, 3])
But not only is it more verbose (requires an additional import), I would argue that it's harder to understand what's really happening behind.
This would also work:
Field('a') == [1, 2, 3]
But again, it feels more "magical" and confusing, because it doesn't respect the semantics of ==.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With