我刚刚发现了 Python 3.11 的新功能,如 ExceptionGroup 和 TaskGroup,我对以下 TaskGroup 行为感到困惑:如果组内的一个或多个任务失败,则所有其他正常任务都将被取消,我没有机会更改该行为 示例:
async def f_error():
raise ValueError()
async def f_normal(arg):
print('starting', arg)
await asyncio.sleep(1)
print('ending', arg)
async with asyncio.TaskGroup() as tg:
tg.create_task(f_normal(1))
tg.create_task(f_normal(2))
tg.create_task(f_error())
# starting 1
# starting 2
#----------
#< traceback of the error here >
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,我无法打印“ending 1”和“ending 2”。asyncio.gather(return_exceptions=True)同时,在发生错误时提供类似选项不取消剩余任务的选项将非常有用。
你可以说“如果你不想要这种取消行为,就不要使用TaskGroup”,但答案是我想使用新的异常组功能,并且它严格绑定到TaskGroup
所以问题是:
给出以下最小示例:
class Association(Base):
__tablename__ = "association_table"
left_id = Column(ForeignKey("left_table.id"), primary_key=True)
right_id = Column(ForeignKey("right_table.id"), primary_key=True)
first_child = Column(Boolean, nullable=False)
child = relationship("Child", back_populates="parents")
parent = relationship("Parent", back_populates="children")
class Parent(Base):
__tablename__ = "left_table"
id = Column(Integer, primary_key=True)
children = relationship("Association", back_populates="parent")
class Child(Base):
__tablename__ = "right_table"
id = Column(Integer, primary_key=True)
parents = relationship("Association", back_populates="child")
Run Code Online (Sandbox Code Playgroud)
如何限制只有一个孩子可以成为父母的第一个孩子?(忽略“夫妇第一个孩子”的逻辑)