I'm trying to determine the best way to implement my application where there will be a main program (main.py) and a separate rules module (rules.py) where an arbitrary number of rules can be written and they will all be applied in main.py to manipulate some data (a dictionary). A user of the application could add their custom rules in rules.py without impacting the logic in main.py.
I was thinking decorators would be useful here to register each function in rules.py in a way that main.py could iterate over them, but I'm not certain of the exact implementation. Here is my skeleton code.
main.py
import rules
modifiers = [] # List of fuctions to modify data
def add_modifier(f):
modifiers.append(f)
return f
def invoke_modifiers(data):
for modifier in modifiers:
data = modifier(data)
return data
if __name__ == "__main__":
data = {'foo': 'bar'}
print(f"Invoking modifiers on data: {data}")
data = invoke_modifiers(data)
print(f"Done invoking modifiers: {data}")
rules.py
from main import add_modifier
@add_modifier
def mod1(data):
data['foo'] = 'baz'
return data
@add_modifier
def mod2(data):
data['quz'] = 'qux'
return data
But when I execute the code, it doesn't modify my data.
$ python main.py
Invoking modifiers on data: {'foo': 'bar'}
Done invoking modifiers: {'foo': 'bar'}
So my questions are two-fold:
- Is this a good way to go about having user-defined functions outside of the main application?
- What needs to change to get the data to be modified by mod1 and mod2 in the rules.py module?
EDIT
If I omit the from main import add_modifier in rules.py, I get the following during execution:
Traceback (most recent call last):
File "main.py", line 3, in <module>
import rules
File "/home/telorb/Python/registerTest/rules.py", line 3, in <module>
@add_modifier
NameError: name 'add_modifier' is not defined