我有一个称为“规则”的类对象数组。
self.rules看起来像这样
[<creative_task.rules.rules.Rule object at 0x7fde7a33f518>, <creative_task.rules.rules.Rule object at 0x7fde7a33f830>, <creative_task.rules.rules.Rule object at 0x7fde7a33f888>, <creative_task.rules.rules.Rule object at 0x7fde7a33f8e0>]
此Rule类具有方法self.check,用于验证存储在其中的数据。
有很多规则需要验证:相对于数据库中的值,请求的值是MORE,LESS,EQUALS,BETWEEN,POSITIVE,NEGATIVE。
关于self.check函数调用的每个此类规则都会调用Clickhouse数据库以进行自我验证。
基本上,当我需要验证规则数组时,我调用check_all函数来验证所有这样的规则
rules = [在self.rules中对r进行r.check( Assets ,上下文)]
:
def check_all(self, asset: dict, context: dict = None) -> RuleGroupResult:
context = {} if context is None else context
return RuleGroupResult(
identifier=self.identifier,
rules=[r.check(asset, context) for r in self.rules],
groups=[g.check(asset, context) for g in self.groups],
logical_operator=self.logical_operator,
)
这些规则互不依赖。
现在,我想使这种验证成为一个并行过程。因此,我需要为数组中的每个Rule调用Rule.check方法,但是此调用应同时发生
最佳答案
可以使用Pool.map
和operator.methodcaller
相对容易地完成此操作,因为您的参数都相同,并且该方法在每个对象上具有相同的名称:
import multiprocessing as mp # Top of file
from operator import methodcaller
def check_all(self, asset: dict, context: dict = None) -> RuleGroupResult:
context = {} if context is None else context
with mp.Pool() as pool: # Create pool
return RuleGroupResult(
identifier=self.identifier,
rules=pool.map(methodcaller('check', asset, context), self.rules), # Map in parallel
groups=pool.map(methodcaller('check', asset, context), self.groups),
logical_operator=self.logical_operator,
)
关于python - 使用多重处理以自己的方法映射数组的每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59266270/