Newer to Python and am experimenting with creating my own Context Manager for calling Login/Logout methods of a certain REST API. That way I can do other API things and Login/Logout will be handled for me. However, I'm confused on the behavior of the return
statement inside the with
statement in the below code. I would expect it to return back to code execution outside the with
block but it instead exits the entire __enter__
function? Why is that?
# test.py
import requests
class LoginLogoutContextManager:
def __enter__(self):
print("**entered __enter__")
print("Logging in...")
# --- Login --- #
# Let's pretend this GET request
# is the Login Code
self.url = "http://www.google.com"
self.session = requests.Session()
with self.session.get(self.url) as self.response:
print("Start Login attempt (inside WITH but before RETURN)")
return len(self.response.content)
print("Login complete (inside WITH but after RETURN)")
# !!! Login Code finished !!! #
# OK login code is now done and we're out of the WITH statement
print("I would expect the above WITH block to Return to here")
print("!!exiting __enter__")
def __exit__(self, exc_type, exc_value, exc_tb):
print("**entered __exit__")
print("Logging OUT...")
# Logout code goes here
print("!!exiting __exit__")
with LoginLogoutContextManager() as manager:
print("Cool now the Login/Logout API calls are handled for me")
# Does other API things here
print(f"Login attempt response length: {manager}")
# python3 test.py
**entered __enter__
Logging in...
Start Login attempt (inside WITH but before RETURN)
Cool now the Login/Logout API calls are handled for me
Login attempt response length: 14126
**entered __exit__
Logging OUT...
!!exiting __exit__