Missing interfaces in Python...

I V wrongbad at gmail.com
Mon Apr 17 17:40:58 EDT 2006


redefined.horizons at gmail.com wrote:
> I see that Python is missing "interfaces". The concept of an interface
> is a key to good programming design in Java, but I've read that they
> aren't really necessary in Python. I am wondering what technique I can
> use in Python to get the same benefits to a program design that I would
> get with interfaces in Java.

To use interfaces in python, just what you would do in Java, except
don't use interfaces.

To expand on that slightly Zen answer, think about why you use
interfaces in Java. The interface declaration tells the compiler that
your object implements a specific set of functions, or that your
function expects an object that implements these functions. Then, at
run time, the actual type of the object is used to decide what function
to call.

However, python doesn't to any type checking at compile time, so it
just uses the dynamic type of the object to decide what function to
call.

> How would I approach this problem in Python? I think I would use an
> abstract class instead of an interface for IFixable, since Python
> supports multiple inheritance, but I'm not sure this is correct.

Concretely:

class Car:
    def fix(self):
       print "Your car is ready, sir"


class Bus:
    def fix(self):
        print "Your bus is ready, sir"


class Mechanic:
    def repair(self, customer, vehicle):
        vehicle.fix()
        customer.bill()


class Customer:
    def bill(self):
        print "Ouch, that was expensive"


me = Customer()
my_bus = Bus()
my_car = Car()
m = Mechanic()

m.repair(me, my_bus)
m.repair(me, my_car)

Which gives the output:

Your bus is ready, sir
Ouch, that was expensive
Your car is ready, sir
Ouch, that was expensive

If you try and repair something that can't be fixed:

m.repair(me, me)

you get:

Traceback (most recent call last):
  File "test.py", line 30, in ?
    m.repair(me, me)
  File "test.py", line 14, in repair
    vehicle.fix()
AttributeError: Customer instance has no attribute 'fix'

Obviously, you don't want this to happen when people use your program.
Java would check this at compile time, but as python doesn't, you can
write a unit test to check that the object's you want to implement the
relevant functions really do.

def is_fixable(obj):
    try:
        obj.fix
    except AttributeError:
        return False
    return True

assert is_fixable(Car())
assert is_fixable(Bus())
assert not is_fixable(Customer())
assert not is_fixable(Mechanic())




More information about the Python-list mailing list