创建一个新的上下文管理器实例,每X次迭代。

huangapple go评论51阅读模式
英文:

Create a new context manager instance every X iterations

问题

如果我有一个上下文管理器CM,它创建一个新的API会话,那么如何在每使用它的10次迭代中创建一个新的上下文管理器呢?问题在于API只能处理有限数量的请求。

counter = 0
# <某个循环,在计数器达到10时创建新会话>
with new_session() as session:
   # 做一些事情
   counter += 1

我最初的想法是像这样做:if counter % 10 == 0: 创建新会话,但这不会保持会话在整个10次迭代中的有效性。

我不知道如何设置循环。

英文:

Say that I have a context manager, CM, that creates a new API session. How can I create a new context manager every 10 iterations of using it? The issue is that the API can only handle so many requests.

counter = 0
# <some loop make new session when counter reaches 10> 
with new_session() as session:
   # Do stuff 
   counter += 1

My first thought was to do something like if counter % 10 == 0: make new session but that doesn’t preserve the session for the whole 10 iterations.

I can’t figure out how to set up the loop.

答案1

得分: 2

使用循环进行10次迭代 上下文管理器内部。

然后,您可以将整个内容放入另一个循环中,以保持进行多次10次迭代。

keep_going = True

while keep_going:
    with new_session() as session:
        for _ in range(10):
            # 进行操作

要停止,可以在某个时候将 keep_going 设置为 False

如果需要更精细的控制来决定何时停止,可以将所有内容放入一个函数中,并使用 return 语句来退出(请参考 https://stackoverflow.com/questions/189645/how-can-i-break-out-of-multiple-loops)。

英文:

Use a loop for 10 iterations inside the context manager.

Then you can put the whole thing in another loop to keep going for multiples of 10 iterations.

keep_going = True

while keep_going:
    with new_session() as session:
        for _ in range(10):
            # do stuff

To stop, set keep_going to False at some point.

If you need more fine-grained control over when to stop, you could put everything inside a function and use a return statement to exit (see https://stackoverflow.com/questions/189645/how-can-i-break-out-of-multiple-loops).

huangapple
  • 本文由 发表于 2023年2月14日 08:00:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定