Created
November 3, 2011 10:08
-
-
Save afroisalreadyinu/1336183 to your computer and use it in GitHub Desktop.
DSL for simple products and product descriptions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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