Does Class implements Interface?
jgardner at jonathangardner.net
Fri Aug 28 00:22:33 CEST 2009
On Aug 27, 3:09 pm, "Emanuele D'Arrigo" <man... at gmail.com> wrote:
> Apologies, my fault,
No apology is necessary.
> I didn't explain that humans are out of the loop
> entirely. It's only at runtime that the program obtains the class
> object that might or might not conform to an expected interface. In
> fact the program might obtain multiple objects and have to decide
> which one conforms best to the expected interface. Of course I could
> use hasattr() and the inspect module (anything else?) to find out if
> existing attributes and method signatures are those expected. Or I
> could just deal with the exceptions as they are raised. However, if I
> could somehow rely that the object I'm getting has the right methods
> and signatures I could avoid peppering the code with try/except
> I was just wondering then if this has been somewhat dealt with and has
> been wrapped in a neat package, set of functions, recipe or pattern.
Don't bother with introspection using hasattr() and such. Use
exceptions. If the object that is instantiated at run-time doesn't
provide the right interface, throw an exception and direct it to the
This isn't much different than what you'd do if you're writing an app
that expects a string of digits but is instead given a string of non-
digits. Rather than inspecting the string before converting it
(introspection), just try to convert it and catch the exception. Then
handle the exception such that you tell the person who entered the
data, "I wanted numbers, not letters" and allow them to try again.
When you stop asking "Did I get something I expect?" except only when
it is absolutely necessary, then you can get back to writing your
More information about the Python-list