sufficiently pythonic code for testing type of function
fredrik at pythonware.com
Wed Oct 11 11:05:10 CEST 2006
Theerasak Photha wrote:
>> Now the real question : what if the object is not an instance of any of
>> the types, but still support the expected interface ?
> for attribute in ['foo', 'bar', '__baz__']:
> getattr(mystery_object, '__%s__' % attribute)
> except AttributeError:
> # Do sumthin bout it
> Is it wrong to 're-raise' an exception with application-specific
> details within an except clause?
nope, as long as the new exception is provides more accurate information
about what actually happened. something like
raise RuntimeError("the frobnitz failed to catch the kitten")
can be a lot better than a 30-level traceback that ends with a line
looking something like
on the other hand, things like this are all too common:
raise Exception("something happened")
also, checking for __method__ is, in general, not the right way to check
if an object implements a given interface. some types use C-level slots
or alternative hooks to provide functionality, and such things are not
always visible from the outside (Python knows how to use them, though).
so if you can, try doing the operation instead, and catch error (if you
really need to check first, use an idempotent operation, if available).
More information about the Python-list