Error handling in context managers

Terry Reedy tjreedy at udel.edu
Mon Jan 16 17:27:56 EST 2017


On 1/16/2017 1:06 PM, Israel Brewster 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,

This would be like open('bad file') returning None instead of raising 
FileNotFoundError.

> and attempting to use it results in an AttributeError.

Just as None.read would.

Actually, I have to wonder about your claim.  The with statement would 
look for cursor.__enter__ and then cursor.__exit__, and None does not 
have those methods.  In other words, the expression following 'with' 
must evaluate to a context manager and None is not a context manager.

 >>> with None: pass

Traceback (most recent call last):
   File "<pyshell#3>", line 1, in <module>
     with None: pass
AttributeError: __enter__

Is psql_cursor() returning a fake None object with __enter__ and 
__exit__ methods?

-- 
Terry Jan Reedy



More information about the Python-list mailing list