Put it together into a feature-flag / access rule.
Implement the helper evaluate(rule, context) that simply calls rule.interpret(context). Then confirm a composed rule such as
And(Equals("country", "US"), Var("age_verified"))
evaluates correctly against different context dicts. The whole tree is driven by the single interpret contract every node shares.
class Var:
def __init__(self, name):
self.name = name
def interpret(self, context):
return bool(context.get(self.name, False))
class Const:
def __init__(self, value):
self.value = value
def interpret(self, context):
return self.value
class And:
def __init__(self, a, b):
self.a = a
self.b = b
def interpret(self, context):
return self.a.interpret(context) and self.b.interpret(context)
class Or:
def __init__(self, a, b):
self.a = a
self.b = b
def interpret(self, context):
return self.a.interpret(context) or self.b.interpret(context)
class Not:
def __init__(self, expr):
self.expr = expr
def interpret(self, context):
return not self.expr.interpret(context)
class Equals:
def __init__(self, key, value):
self.key = key
self.value = value
def interpret(self, context):
return context.get(self.key) == self.value
def evaluate(rule, context):
"""Evaluate a composed rule tree against a context dict."""
# TODO: return rule.interpret(context)
pass
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
Put it together into a feature-flag / access rule.
Implement the helper evaluate(rule, context) that simply calls rule.interpret(context). Then confirm a composed rule such as
And(Equals("country", "US"), Var("age_verified"))
evaluates correctly against different context dicts. The whole tree is driven by the single interpret contract every node shares.
Press Run Tests or ββ© to check your solution.