CodexBloom - Programming Q&A Platform

Using contextlib.contextmanager for resource management in Python 3.9 leads to unexpected attribute errors

πŸ‘€ Views: 418 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
python-3.x contextlib requests Python

I'm trying to create a context manager with `contextlib.contextmanager` to handle a resource that connects to an external API. However, I'm working with an `AttributeError` when attempting to use the context manager within a `with` statement. Here’s my code: ```python from contextlib import contextmanager import requests @contextmanager def api_connection(url): try: session = requests.Session() response = session.get(url) if response.status_code != 200: raise ValueError(f'behavior: Received status code {response.status_code}') yield response.json() finally: session.close() ``` When I run this code as follows: ```python with api_connection('https://jsonplaceholder.typicode.com/posts/1') as data: print(data) ``` I get the behavior: `AttributeError: 'NoneType' object has no attribute 'json'`. I expected `data` to be the JSON response from the API. I’ve also tried adding print statements within the `api_connection` function to debug the flow, but it seems like the behavior occurs in the `yield` statement. I’ve verified that the URL is correct and reachable. What could be causing this scenario? Is there a better way to manage this kind of resource in Python 3.9? Any help would be appreciated!