Skip to content

Instantly share code, notes, and snippets.

@afroisalreadyinu
Created November 3, 2011 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afroisalreadyinu/1336183 to your computer and use it in GitHub Desktop.
Save afroisalreadyinu/1336183 to your computer and use it in GitHub Desktop.
DSL for simple products and product descriptions
class Product(object):
def __init__(self, color, size, weight):
self.color, self.size, self.weight = color, size, weight
class CombinableQueryMixin(object):
def __and__(self, other):
return CompoundQuery(self, other, anded=True)
def __or__(self, other):
return CompoundQuery(self, other, anded=False)
def __invert__(self):
self.negated = not self.negated
return self
class BasicProductQuery(CombinableQueryMixin):
DIMENSIONS = ['color', 'size', 'weight']
def __init__(self, **kwargs):
dimension, value = kwargs.items()[0]
assert dimension in self.DIMENSIONS
self._dimension = dimension
self._value = value
self.negated = False
def __contains__(self, product):
return (self._value == getattr(product, self._dimension)) != self.negated
class CompoundQuery(CombinableQueryMixin):
def __init__(self, left, right, anded=True):
self._and = anded
self.left, self.right = left, right
self.negated = False
def __contains__(self, product):
op = all if self.negated != self._and else any
if self.negated:
return op([not product in self.left, not product in self.right])
else:
return op([product in self.left, product in self.right])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment