tags:

views:

49

answers:

4

Hi,

Would it be possible to create a class interface in python and various implementations of the interface.

Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want to wrap it to adhere to a contract.

In the future, if I want to use another component or code my own, I want to be able to swap things out and not have things very tightly coupled.

Possible? I'm new to python.

A: 

Yes, this is possible. There are typically no impediments to doing so: just keep a stable API and change how you implement it.

Mike Graham
+1  A: 

Of course. There is no need to create a base class or an interface in this case either, as everything is dynamic.

Yann Ramin
+3  A: 

For people coming from a strongly typed language background, Python does not need a class interface. You can simulate it using a base class.

class BaseAccess:
  def open(arg):
    raise NotImplementedError()

class Pop3Access(BaseAccess):
  def open(arg):
    ...

class AlternateAccess(BaseAccess):
  def open(arg):
    ...

But you can easily write the same code without using BaseAccess. Strongly typed language needs the interface for type checking during compile time. For Python, this is not necessary because everything is looked up dynamically in run time. Google 'duck typing' for its philosophy.

There is a Abstract Base Classes module added in Python 2.6. But I haven't have used it.

Wai Yip Tung
Thanks msw. I don't know one user can edit the response for another user :)
Wai Yip Tung
Yes, but only for the forces of good. Actually, that was on a whim because I couldn't say anything you hadn't in your well written reply. http://stackoverflow.com/faq (near the bottom)
msw
A: 

One option is to use zope interfaces. However, as was stated by Wai Yip Tung, you do not need to use interfaces to achieve the same results.

The zope.interface package is really more a tool for discovering how to interact with objects (generally within large code bases with multiple developers).

tgray