0

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.

1
  • You could also patch one version of PyGrSQL with pg.Error = pg.error, especially if you think you're going to drop support for one version later. Feb 26, 2016 at 15:13

3 Answers 3

2

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
0

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:
   ...
0

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.

4
  • 1
    This is very confusing, I would not use this in a real project. Feb 26, 2016 at 15:11
  • If you insist. :( Thank you for actually saying something instead of just down-voting. If it were my site, I would make it a rule that every downvote on a post should be accompanied either with a comment or an up-vote on someone else's comment. Mine does have the advantage of being on one line, but I can see how you would prefer the other method. I just don't see why a method that someone doesn't like should be down-voted. How I see it, if you don't like it, don't use it. Posts should be down-voted if they don't answer the question, or if they use an off-site resource, etc., but I rant.
    – zondo
    Feb 26, 2016 at 15:16
  • You just made me feel bad. :-( I agree, a comment would have been sufficient. Sorry about that. Feb 26, 2016 at 15:22
  • I didn't mean to make you feel bad. I thought it was someone else :)
    – zondo
    Feb 26, 2016 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.