On 29Nov2010 18:22, Bill Janssen firstname.lastname@example.org wrote: | Nick Coghlan email@example.com wrote: | > As far as the original post's request goes, no. issubclass expects to | > be given two types. If you have an insanely polymorphic variable that | > can contain a wide variety of objects, only some of which are type | > instances, then either use isinstance to check first as you are | > already doing, or a try-except block to convert the TypeError to a | > False result (and bundle the combined test into a helper function if | > you're doing it a lot). | | Right. Use isinstance instead; that's what it's there for. | | But handling exceptions properly really requires thinking about which | might occur, and what to do if they do occur. If you don't do that | preemptive thinking about exceptionality, you might as well not bother | catching them at all.
My problem with try/except (which leads me to be reluctant to use it except around really really simple things) is that you don't know what threw the exception.
if obj.foo == 0: # handle 0 else: x = y / obj.foo
The try/except verision goes like this:
try: x = y / obj.foo except ZeroDivisionError: # handle 0
Now, the reason I'm using "obj.foo" here is that obj.foo may be a property or otherwise inplemented by __getattr__; arbitrarily complex code may be happening to obtain the value it returns. The upshot of that is that even this very simple looking code may be an unhandled ZeroDivisionError from deeper in the call stack - I don't know it came from the division visible in the code example above.
For this reason, I will usually prefer to go the if/else route, and if I go the try/except route I will often have a lot of leading gumph to get everything into purely local variables just to avoid the risk shown above:
z = obj.foo # gumph try: x = y / z except ZeroDivisionError: # handle 0
The obfuscation from the leading gumph can often outweigh the brazen pleasures of the try/except leap into the unknown:-)