1

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
bobglu
  • 61
  • 5

1 Answers1

2

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 How can I break out of multiple loops?).

mkrieger1
  • 19,194
  • 5
  • 54
  • 65