Error handling in context managers

Israel Brewster israel at ravnalaska.net
Tue Jan 17 13:59:16 EST 2017


On Jan 16, 2017, at 11:34 PM, Peter Otten <__peter__ at web.de> wrote:
> 
> Gregory Ewing wrote:
> 
>> Israel Brewster wrote:
>>> The problem is that, from time to time, I can't get a connection, the
>>> result being that cursor is None,
>> 
>> That's your problem right there -- you want a better-behaved
>> version of psql_cursor().
>> 
>> def get_psql_cursor():
>>    c = psql_cursor()
>>    if c is None:
>>       raise CantGetAConnectionError()
>>    return c
>> 
>> with get_psql_cursor() as c:
>>    ...
> 
> You still need to catch the error -- which leads to option (3) in my zoo, 
> the only one that is actually usable. If one contextmanager cannot achieve 
> what you want, use two:
> 
> $ cat conditional_context_raise.py
> import sys
> from contextlib import contextmanager
> 
> class NoConnection(Exception):
>    pass
> 
> class Cursor:
>    def execute(self, sql):
>        print("EXECUTING", sql)
> 
> @contextmanager
> def cursor():
>    if "--fail" in sys.argv:
>        raise NoConnection
>    yield Cursor()
> 
> @contextmanager
> def no_connection():
>    try:
>        yield
>    except NoConnection:
>        print("no connection")
> 
> with no_connection(), cursor() as cs:
>    cs.execute("insert into...")
> $ python3 conditional_context_raise.py
> EXECUTING insert into...
> $ python3 conditional_context_raise.py --fail
> no connection
> 
> If you want to ignore the no-connection case use 
> contextlib.suppress(NoConnection) instead of the custom no_connection() 
> manager.

Fun :-) I'll have to play around with that. Thanks! :-)

-----------------------------------------------
Israel Brewster
Systems Analyst II
Ravn Alaska
5245 Airport Industrial Rd
Fairbanks, AK 99709
(907) 450-7293
-----------------------------------------------
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list