4 ms·
Isn't this simply a bug? Why would hasattr() catch all exceptions instead of just AttributeError? IMHO a better title would be: "Python2 hasattr() has a bug".
by annnnd 11y ago
Isn't this simply a bug? Why would hasattr() catch all exceptions instead of just AttributeError? IMHO a better title would be: "Python2 hasattr() has a bug".
- ggreer 11y agoNot a bug, just Python 3 choosing different trade-offs. getattr() and hasattr() are useful for replacing annoying boilerplate like: try: foo = x.y except Exception: foo = None If getattr() and hasattr() can raise, then you have to wrap them in try/except blocks. So much for that previously useful shorthand. There's no good solution here. Either hasattr() can raise (confusing), or it can return false for attributes that exist (also confusing). Maybe if the name was changed (validattr()?), everyone would be OK with the Python 2 behavior.
- alkonaut 11y agoI prefer the Python2 solution actually. If we disregard for a moment the madness of "hasattr" actually invoking the attribute code -- if it does invoke it and an error occurs, hasn't that proven that the attribute does in fact exist? Picture a type that has a "t.connect()" function, and a "t.data" attribute. The data attribute will fail if connect() hasn't been called prior to accessing it. I'd expect hasattr(t, "data") to answer true and never raise an error, regardless of when I do it. The only way to do that (if you have to invoke the code in the attribute -- not sure if that is the case) is to catch and return true. Validattr would have been a much better name, yes.
- annnnd 11y agoMaybe i wasn't clear enough, I think the bug is this line: except Exception: Why would you want to catch all exceptions? ideally you should catch just those that are applicable to your case and ignore others: except AttributeError: