I have an example:
import requests
with requests.Session() as s:
s.get('http://python.su/')
Does requests.get use the same structure as this example?
Can you give me examples where with statement is required?
As explained in the documentation, the Session() can be used as a context manager to be able to close it and all the underlying used adapters in a clean fashion:
Sessions can also be used as context managers:
with requests.Session() as s: s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')This will make sure the session is closed as soon as the with block is exited, even if unhandled exceptions occurred.
The Session can and is supposed to be shared across multiple requests persisting cookies and other parameters and reusing the same TCP connection, but the requests.get() on the other hand is just a single call that would produce a single Response instance - there is no point in context manager for it.
Please read the following to get a better understanding of Context Managers:
If you read the documentation for requests.Session
Sessions can also be used as context managers:
with requests.Session() as s: s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')This will make sure the session is closed as soon as the with block is exited, even if unhandled exceptions occurred.
Making use of the with statement is a common idiom in Python to handle context management:
The
withstatement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers). This allows commontry...except...finallyusage patterns to be encapsulated for convenient reuse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With