Error handling in context managers

Chris Angelico rosuav at gmail.com
Mon Jan 16 13:25:54 EST 2017


On Tue, Jan 17, 2017 at 5:06 AM, Israel Brewster <israel at ravnalaska.net> wrote:
> I generally use context managers for my SQL database connections, so I can just write code like:
>
> with psql_cursor() as cursor:
>     <do whatever>
>
> And the context manager takes care of making a connection (or getting a connection from a pool, more likely), and cleaning up after the fact (such as putting the connection back in the pool), even if something goes wrong. Simple, elegant, and works well.
>
> The problem is that, from time to time, I can't get a connection, the result being that cursor is None, and attempting to use it results in an AttributeError.

My question is: If you can't get a connection, why do you get back
None? Wouldn't it be better for psql_cursor() to raise an exception?

ChrisA



More information about the Python-list mailing list