Waslap
Waslap

Reputation: 571

Python handle unknown types graciously

I have a problem where I need to have the same piece of code depend on two different versions of PyGreSQL. The problem is the one version has an exception error (lowercase) and the other version exception Error (uppercase). How can I handle this gracefully. If I have:

try:
    do_something
except pg.error, x:
    print "Database connection error: ", x
except pg.Error, x:
    print "Database connection error: ", x

then I invariably run into a problem when Error is thrown as it passes error first and error is not known. Is there a way in Python to deal with this ?

I mean in C++ one could have pre-processor conditionals to deal with it but in Python I have no clue how.

This all due to some infinitely wise man somewhere changing the case between versions.

Upvotes: 0

Views: 101

Answers (3)

zondo
zondo

Reputation: 20346

You could say this:

except getattr(pg, ("error", "Error")[hasattr(pg, "Error")]) as x:

It uses that handy feature where a true value is 1 and a false value is 0. That way, if pg has an attribute called Error, it uses getattr(pg, [("error", "Error")[1])) which simplifies to getattr(pg, "Error") or pg.Error. If it does not have that attribute, through the same simplification we can see that it uses pg.error.

Upvotes: 0

dsh
dsh

Reputation: 12214

You could solve it during import, which would also simplify your code:

import pg
try:
    pgError = pg.error
except AttributeError:
    pgError = pg.Error

Then later:

try:
    ...
except pgError, e:
    print e

Upvotes: 2

deceze
deceze

Reputation: 522412

Experimentally determine the exception type before the actual try..catch:

try:
    exception_type = pg.error
except AttributeError:
    exception_type = pg.Error

try:
   ...
except exception_type:
   ...

Upvotes: 0

Related Questions