注意: 这个问题与 Python 的 FSM 库pytransitions 有关
我正在寻找一种方法来按顺序解决方法回调,当它们在prepare or/and before or/and after中作为列表被提及时。我正在使用AsyncMachine来自的模块transitions.extensions.asyncio
预期结果:
1Done_2Done_3Done
得到:
None_3Done
复制当前情况的示例代码:
import asyncio
from transitions.extensions.asyncio import AsyncMachine
class Model:
STATES = ['A', 'B']
TRANSITIONS = [
{'trigger': 'next', 'source': 'A', 'dest': 'B',
'prepare': ['initialize1', 'initialize2', 'initialize3'], 'before': [], 'after': ['show_attributes']}
]
def __init__(self, name, state='initial'):
self.name = name
self.state = state
self.attribute_1 = None
self.attribute_2 = None
self.attribute_3 = None
async def initialize1(self):
await asyncio.sleep(1) # This is expensive operation and will take some time.
self.attribute_1 = '1Done'
print(f'{self.name} {self.state} -> Initialized1: ', self.attribute_1)
async def initialize2(self):
await asyncio.sleep(0.5) # This is expensive operation and will take some time.
self.attribute_2 = f'{self.attribute_1}_2Done'
print(f'{self.name} {self.state} -> Initialized2: ', self.attribute_2)
async def initialize3(self):
self.attribute_3 = f'{self.attribute_2}_3Done'
print(f'{self.name} {self.state} -> Initialized3: ', self.attribute_3)
async def show_attributes(self):
print(f'{self.name} {self.state} -> Showing all: {self.attribute_3}')
machine = AsyncMachine(
model=None,
states=Model.STATES,
transitions=Model.TRANSITIONS,
initial=None,
queued='model'
# queued=True
)
async def main():
model1 = Model(name='Model1', state='A')
machine.add_model(model1, initial=model1.state)
await machine.dispatch('next')
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(main())
正如代码中所示,'prepare': ['initialize1', 'initialize2', 'initialize3']我正在寻找一种方法,一旦解决了 initialize1 就调用 initialize2 ,一旦解决了 initialize1 和 initialize2 方法,就调用 initialize3 。目前,它们被并行调用,这是一个很好的特性,但如果有一种方法可以让它们按顺序执行/解析,那就太棒了。
当然,我可以再添加一个方法initialize_all,然后在其中调用上述所有方法。但是想想我要不断添加多少新方法来处理现实世界的问题。我想让我的函数可重用且更小,仅用于特定任务。