Business Rules

1.1.1 · active · verified Thu Apr 16

Business Rules is a Python Domain Specific Language (DSL) that allows you to define business intelligence rules without writing direct code. It provides a framework for defining 'variables' (data points) and 'actions' (operations) and then executing JSON-defined rules against them. The current stable version is 1.1.1, with releases occurring infrequently for maintenance and compatibility updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define variables that retrieve data from an object, define actions that modify the object, and then execute a set of rules (defined in a JSON-like dictionary) against that object using `run_all`. The rules check if a numeric variable is greater than 10 AND if a text variable contains 'hello'. If both conditions are true, a specified action is triggered.

from business_rules.actions import BaseActions, rule_action
from business_rules.fields import FIELD_NUMERIC, FIELD_TEXT
from business_rules.variables import BaseVariables, rule_variable
from business_rules.run_all import run_all

# 1. Define your data source (variables)
class SomeVariables(BaseVariables):

    def __init__(self, some_object):
        self.some_object = some_object

    @rule_variable(FIELD_NUMERIC)
    def some_numeric_variable(self):
        return self.some_object.some_numeric_value

    @rule_variable(FIELD_TEXT)
    def some_text_variable(self):
        return self.some_object.some_text_value

# 2. Define actions to take when rules are met
class SomeActions(BaseActions):

    def __init__(self, some_object):
        self.some_object = some_object

    @rule_action(params=[{'fieldType': FIELD_NUMERIC, 'name': 'some_param'}])
    def some_action(self, some_param):
        self.some_object.some_action_has_run = True
        self.some_object.some_action_param = some_param

# Example object to apply rules to
class MyDataObject:
    some_numeric_value = 15
    some_text_value = "hello world"
    some_action_has_run = False
    some_action_param = None

my_data_object = MyDataObject()

# 3. Define your rules in a JSON-like structure
rules = [{
    "conditions": {
        "all": [
            {
                "name": "some_numeric_variable",
                "operator": "greater_than",
                "value": 10
            },
            {
                "name": "some_text_variable",
                "operator": "contains",
                "value": "hello"
            }
        ]
    },
    "actions": [
        {
            "name": "some_action",
            "params": {"some_param": 123}
        }
    ]
}]

# 4. Run the rules
run_all(
    rules=rules,
    defined_variables=SomeVariables(my_data_object),
    defined_actions=SomeActions(my_data_object),
    stop_on_first_failure=False
)

print(f"Action has run: {my_data_object.some_action_has_run}")
print(f"Action parameter: {my_data_object.some_action_param}")

view raw JSON →