Error handling in context managers

Israel Brewster israel at ravnalaska.net
Tue Jan 17 13:54:08 EST 2017


On Jan 16, 2017, at 1:27 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> 
> 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?

No, the *context manager*, which I call in the with *does* have __enter__ and __exit__ methods. It's just that the __enter__ method returns None when it can't get a connection. So the expression following with *does* evaluate to a context manager, but the expression following as evaluates to None.

-----------------------------------------------
Israel Brewster
Systems Analyst II
Ravn Alaska
5245 Airport Industrial Rd
Fairbanks, AK 99709
(907) 450-7293
-----------------------------------------------

> 
> -- 
> Terry Jan Reedy
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list