[Tutor] intefaces in python
Dave Angel
davea at ieee.org
Mon Jun 29 13:31:01 CEST 2009
Amit Sethi wrote:
> Well I want to implement plug-in like mechanism for an application . I want
> to define some minimum functions that any body writing a plugin has to
> implement. For that i thought an interface would be best because in a
> scenario where the function is not implemented some kind of error would
> occur. I would love to hear if you think their is a better way to achieve
> this
In Java, deriving a class from such an interface, but neglecting to
implement those methods will cause a compile error (if I recall
correctly, it's been several years). In Python, the error will happen
at run time. But an existing runtime error will occur even without such
an interface, so it wouldn't seem you gain much. In Python, the
interface does two things:
1) it's a comment, a common place to look for certain behavior.
2) it's potentially a source for an IDE to provide tool-tips or code
completion
3) it can generate a different error, which is perhaps more useful to
the developer unsure of how the method is spelled or used. This way
he/she knows whether to fix the caller or the implementation.
#3 seems valid to me.
However, for the particular use-case, you might want to stretch a bit
further. Since you've got one "user" (your code), and many "providers"
(the plug-in writers) perhaps you could arrange that when the plugin is
first encountered, you validate that it has all the required methods and
data members. Not by calling them, but by scanning the object for their
existence.
More information about the Tutor
mailing list