Python "implements <interface>" equivalent?

Terry Reedy tjreedy at udel.edu
Thu Oct 4 18:28:15 EDT 2007


"Wojciech Gryc" <wojciech at gmail.com> wrote in message 
news:1191510706.528876.261780 at 57g2000hsv.googlegroups.com...
| Hi,
|
| I recently started using Python and am extremely happy with how
| productive it's made me, even as a new user. I'm hoping to continue
| using the language for my research, and have come across a bit of a
| stumbling block.
|
| I'm a seasoned Java programmer and quite a big fan of interfaces...
| i.e. The idea that if I make a number of distinct classes that
| implement interface X, I can pass them all as parameters to functions
| or whatnot that require an X object.
|
| Is there something similar in Python?

As others have noted, without typechecks, Python code is generic.  For 
example, 'a+b' means "Try a.__add__(b).  If that does not work, try 
b.__radd__(a).  If that does not, raise an error."

| What I'd like to do is create a feature detection system for my work
| -- specifically, a general class / interface called "Feature" and then
| subclasses that implement functions like isFeaturePresent() in all of
| their different and unique ways. I'd love to hear how I can do this in
| Python.

If you have several methods (with multiple implementations), an abstract 
base class can be helpful:

class Feature(object):
    def isFeaturePresent(self):
        raise NotImplementedError
    def otherMethod(self):
        raise NotImplementedError
    # etc

Inherit from Feature (and possibly other classes -- Python has multiple 
inheritance) to make your subclasses.  Then put 'if not isinstance(arg, 
Feature): raise TypeError(func requires Features)' at the top of functions 
that work on Features.  If you call Feature methods more than once in a 
function, this save multiple checks or try-except blocks.

The cost, of course, is the inheritance requirement.

Terry Jan Reedy






More information about the Python-list mailing list