I would like to use an object as a context manager, but control the moment when the __exit__
method is called.
In particular, I am using the Session()
object offered by the Python requests module, which can be used as a context-manager. I understand that by simply using e.g. requests.get()
a new Session()
object is created and destroyed each time, while instead persisting a session should give a shorter response time and keep headers, etc for all requests within the session. I would like to make x
requests with a Session()
, then close the session and make y
requests with a new Session()
object, and so on until my code has finished running. However, since I have various calls to Session().get()
in my code, I do not want to have it all contained within a with
block. What are my options?
This is probably a simple problem for more experienced Python programmers, but I find myself stuck in figuring out how to organise my code. Any ideas about how this could be implemented? Happy to give any clarifications if needed. Thanks.