check if class really implements api?

Heiko Wundram modelnine at bit-bukket.org
Tue Jan 3 20:30:00 EST 2006


Karsten W. wrote:
> However, I find myself constantly changing the API and I am looking for
> a more reliable way
> to check my implementation classes. Is there a way to check if at least
> all function
> names of the API are defined by the class and if their parameter lists
> fit the API? A way
> to test this would save me a lot of time..

To make it short: no, there is no reliable way to test this.

To make it longer: yes, you can, with several kludges (and limitations),
test this sort of thing. For example, start by running a dir() on the
interface definition class, and for each name you get returned check
whether it is a callable/function, then in case it is, have a look at the
corresponding class claiming to implement the interface, check if the name
exists, if it is a callable, and whether the method signature is
appopriately similar.

Most of the latter can be done using the introspection support present in
Python, which is nicely wrapped up for you in a module and whose
documentation you can find at:

http://www.python.org/doc/2.4.2/lib/module-inspect.html

Be aware that this does not check for methods which might be added at
runtime to a class, that you might have to create more elaborate tests to
check whether a class that might be callable has the correct method
signature, and several other quirks (such as a function in the interface
prototype taking five arguments, whereas in the class definition taking
only a single catch-all argument).

See how much of a can of worm this is? That's why you should rely on
duck-typing: if it quacks like a duck and walks like a duck, chances are
you really have a duck. And the only reliable way to test that is to let it
run.

--- Heiko.



More information about the Python-list mailing list