On Sun, Nov 28, 2010 at 4:13 PM, Steven D'Aprano email@example.com wrote:
Unfortunately it would be a backwards incompatible change. Currently catching the TypeError from issubclass is a way of detecting that an object *isn't* a type.
Who is doing that?! What's wrong with something like `isinstance(thing, (type, types.ClassType))`?
Is that a serious question? Trying something, and catching the exception if it fails, is a general Python idiom. In many case, it's often considered more "pythonic" to write:
try: handle normal case (which might fail) except SomeException: handle exceptional case
if operation will fail: handle exceptional case else: handle normal case (which hopefully won't fail)
since at least Python 1.5. It's been long considered "best practice" under many circumstances to catch exceptions rather than to try to preemptively guess what might go wrong.
Hm. The try/except version should IMO be used as a last resort only (similar to using eval() / exec()). It usually reads more clumsily than the if-based version, and often it is not clear to the reader what error condition is being tested. One of the most common things I see in Python code reviews at work is try/except clauses that catch an overly general exception and/or out a try/except around an overly long piece of code, masking potential errors and obscuring the meaning of the code. (Another common one is legitimate try/except clauses that are nevertheless lacking a comment explaining what error condition is being caught and why.)
That is not to say that try/except should not be used, but I think the question of what's wrong with an explicit test should not be cast off as rhetorical.
As to the original issue, Antoine got it: issubclass(X, Y) does not make sense if you're not even sure that X is a class.