所以我想实现一个过滤器,它检查输入并匹配过滤器参数中提供的逻辑
import operator
class InvalidQuery(Exception):
pass
class Filter(object):
binary_operators = {
u"==": operator.eq,
u"<": operator.lt,
u">": operator.gt,
u"<=": operator.le,
u">=": operator.ge,
u"!=": operator.ne,
}
multiple_operators = {
u"or": any,
u"and": all,
}
def __init__(self, tree):
self._eval = self.build_evaluator(tree)
def __call__(self, **kwargs):
return self._eval(kwargs)
def build_evaluator(self, tree):
try:
operator, nodes = list(tree.items())[0]
except Exception:
raise InvalidQuery("Unable to parse tree %s" % tree)
try:
op = self.multiple_operators[operator]
except KeyError:
try:
op = self.binary_operators[operator]
except KeyError:
raise InvalidQuery("Unknown operator %s" % operator)
assert len(nodes) == 2
def _op(values):
return op(values[nodes[0]], nodes[1])
return _op
elements = [self.build_evaluator(node) for node in nodes]
return lambda values: op((e(values) for e in elements))
x = Filter({"and": (
{"==": ("y", "abc")},
{"==": ("y", "qwerty")},
)})
print(x(y='abc', y='qwerty'))
这项工作:
print(x(y='abc'))
这并不是:
print(x(y='abc', y='qwerty'))
我要做的是将逻辑传递给构造函数,并希望在传递给方法的输入上运行逻辑。 输入可以有多个具有相同名称和不同值的键。 请帮忙。 谢谢
目前没有回答
相关问题 更多 >
编程相关推荐