Как прокомментировали, вы довольно близки.Все, что вам нужно сделать, это вызвать rule
во время итерации.
Что касается обработки параметров различной длины, вы можете использовать *args
и **kwargs
в своих правилах.Вот краткий пример:
def rule1(*args, **kwargs):
# Handling of non-keyword params passed in, if any
if args:
for arg in args:
print(f'{arg} is type {type(arg)}')
# if kwargs is not necessary if you don't intend to handle keyword params
def rule2(*args, **kwargs):
# if args is not necessary if you don't intend to handle non-keyword params
# handling of keyword params passed in, if any
if kwargs:
for k, v in kwargs.items():
print(f'Keyword arg {k} has value {v}')
rule_book = [rule2, rule1]
for rule in rule_book:
# iterate through the rule_book with the same amount of args and kwargs
rule('I am a string', 123, ('This', 'is', 'Tuple'), my_list=[0, 1, 2], my_dict={'A': 0, 'B': 1})
Результат:
Keyword arg my_list has value [0, 1, 2]
Keyword arg my_dict has value {'A': 0, 'B': 1}
I am a string is type <class 'str'>
123 is type <class 'int'>
('This', 'is', 'Tuple') is type <class 'tuple'>
Ключ к выводу - сохранить соответствие параметров вашим правилам, как только все будет передано,просто возьмите соответствующий объект и используйте его:
def rule3(*args, **kwargs):
if args:
for arg in args:
if isinstance(arg, tuple):
# if there's a tuple presented, reverse each of the inner items
print([a[::-1] for a in arg])
# ['sihT', 'si', 'elpuT']
Благодаря тому, как вы структурировали свой код, я уверен, что вы сможете понять и применить его к своему собственному.