Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: catching particular exception

I have such code (Python 2.5, GAE dev server):

try:
    yt_service.UpgradeToSessionToken() // this line produces TokenUpgradeFailed
except gdata.service.TokenUpgradeFailed:
    return HttpResponseRedirect(auth_sub_url()) # this line will never be executed (why?)
except Exception, exc:
    return HttpResponseRedirect(auth_sub_url()) # instead this line is executed (why?)

So I set breakpoint at last line and under debugger I see:

"exc"   TokenUpgradeFailed: {'status': 403, 'body': 'html stripped', 'reason': 'Non 200 response on upgrade'}   
"type(exc)" type: <class 'gdata.service.TokenUpgradeFailed'>
"exc is gdata.service.TokenUpgradeFailed"   bool: False 
"exc.__class__" type: <class 'gdata.service.TokenUpgradeFailed'>
"isinstance(exc, gdata.service.TokenUpgradeFailed)" bool: False 
"exc.__class__.__name__"    str: TokenUpgradeFailed 

What I missed in python exception handling? Why isinstance(exc, gdata.service.TokenUpgradeFailed) is False?

like image 821
Vladimir Mihailenco Avatar asked Sep 24 '26 04:09

Vladimir Mihailenco


1 Answers

This error can occur if your relative/absolute import statements do not match everywhere. If there is a mismatch, the target module can be loaded more than once and in slightly different contexts. Usually this isn't a problem but it does prevent classes from the differently loaded modules from comparing as equal (hence the exception catching problem).

There may be other causes for the error but I suggest looking through your code and ensuring that everything importing the gdata.service module explicitly mentions the gdata package. Even within the gdata package itself, each module using the service module should import it from the package explicitly via from gdata import service rather than by way of the relative import: import service.

like image 51
Rakis Avatar answered Sep 25 '26 18:09

Rakis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!