You are not logged in Log in Join
You are here: Home » Zope Documentation » Books » The Zope Developer's Guide Releases » Zope Developer's Guide (2.4 edition) » Components and Interfaces

Log in
Name

Password

 
Previous Page Up one Level Next Page Components and Interfaces Comments On/Off Table of Contents

Chapter 1: Components and Interfaces

Zope is becoming a component system. Zope components will be Python objects with interfaces that describe them. Right now only some of the Zope code base uses interfaces. In coming releases more and more of Zope will include interfaces. As a Zope developer you can use interfaces right now to build your Zope components.

Anonymous User - Jan. 24, 2002 6:48 am - I would move this chapter to the end, because you don't need it to get
the first "hello world" python product.
Anonymous User - Jan. 29, 2003 8:59 am:
 (After rading this chapter)Is it ZopeDG or PythonDG???
Anonymous User - Nov. 5, 2003 2:59 pm:
 This user comment thing is good. But what would be nice is a user "moderation" which can optionally provide
 some users with ability to filter some comments off, so we can get on with the document.

 Still, this whole thing is cool. Cant believe I have heard of Zope all these days and never gave it a shot
 thinking
 its nothing but another hype :(

 Sorry !
Anonymous User - Nov. 23, 2003 10:20 am:
 Maybe you can get a first tutorial about how to write a very minimal product at:
 http://www.zope.org/Members/maxm/HowTo/minimal_01/
 Don't know if it helps. I'm just going through it.
Anonymous User - June 8, 2004 11:29 am:
 just another comment!
 These comments are usefull?
 Karluz

Zope Components

Components are objects that are associated with interfaces. An interface is a Python object that describes how you work with other Python objects. In this chapter, you'll see some simple examples of creating components, and a description of interfaces and how they work.

Anonymous User - Feb. 27, 2003 6:20 am:
 werwer
Anonymous User - Apr. 26, 2004 7:27 am:
 Привет!
Anonymous User - Aug. 25, 2004 12:01 pm:
 Norok tavarisch !
Anonymous User - Sep. 12, 2005 4:54 pm:
 111

Here is a very simple component that says hello. Like all components, this one generally consists of two pieces, an interface, and an implementation:


from Interface import Base

class Hello(Base):
    """ The Hello interface provides greetings. """

    def hello(self, name):
        """ Say hello to the name """

class HelloComponent:

    __implements__ = Hello

    def hello(self, name):
        return "hello %s!" % name
Chris Gray - Aug. 23, 2002 12:44 pm:
 This information and these sorts of examples as presented here by themselves are all but useless to someone
 very new to Zope development. Where do these classes go? How do I install them in Zope? How do you
 instantiate the classes? How do you access the instantiations? How can I experiment with this code? You seem
 to be presenting all the high-level information without any practical information on how you actually put it
 to use. The equivalent would be a beginner's book on Python that assumed you would read the source code for
 the interpreter to discover how to invoke it. It seems to me there is a large gap between what you would
 learn from the Zope Book and what you need to make use of the information presented here.
Anonymous User - Oct. 3, 2002 5:15 am:
 I must say I have to agree with Chris.
 A few days ago I picked up a PHP book, and in 20 minutes I was up and running with my first PHP code
 snippets.
 I'm keen to choose Zope because I've been using Python for while but all this documentation is so nebulous!
 I've been reading for days and am still totally vague as to how to get even something elementary happening.
 I know there are fabulous people behind Zope and Python. I wish they could hear comments such as those of
 Chris'.
Anonymous User - Oct. 4, 2002 12:29 pm:
I'm sure you were up and running quickly with PHP. But it's likely that you could have been up and running in
 Zope as well in the same amount of time by reading the Zope Book. My advice is to not read this guide until
 you've thoroughly read the Zope Book and done a little Zope development.
 Zope is loosely the equivalent of PHP, Apache, and Oracle wrapped up into a single piece of software, so it
 makes sense that it would take more time to grok than straight PHP. That said, there is a gap between the
 Zope Book and this guide. It's likely that that gap will need to be filled by 3rd-party published books.
Anonymous User - Nov. 11, 2002 3:39 am:
 New developers can be attracted to hacking code, by allowing them to see the key points of technology are.
 With this example as many other ones, -> zope book, web,
there is alot of information missing, as one can learn from inferred data from other places. This just sucks.
 I love python, because it is consice, to the point,
 with this stuff, its just superfrustrating. very many people i know gave up, because they wanted all the
 details, and all they were given is a gobs of vague ideas, and some code that did not relate, as in between
 examples, so it was hard to make out what the hell is going on.
Anonymous User - Dec. 3, 2002 1:06 am:
 The COM OFF button rules.
exdesign - Jan. 9, 2003 10:31 pm:
 Just opened __init__.py in /lib/python/Interface for Zope 2.6.0. It says:

 <begin quote from /lib/python/Interface/__init__.py>

 This package implements the Python "scarecrow" proposal.

 The package exports a single name, 'Interface' directly. Interface
 is used to create an interface with a class statement, as in:

   from Interface import Interface

   class IMyInterface(Interface):
     '''Interface documentation
     '''

     def meth(arg1, arg2):
         '''Documentation for meth
         '''

     # Note that there is no self argument

 To find out what you can do with interfaces, see the interface
 interface, IInterface in the IInterface module.

 <snip>

 Revision information:
 $Id: __init__.py,v 1.9 2002/08/14 21:35:32 mj Exp $
 """

 from _Interface import Interface
 from Attribute import Attribute
 Base = Interface # XXX We need to stamp out Base usage

 <end>

From this I infer that this page is not only nebulous, but very much out of date; both the self arguments and
 the use of the Base term are deprecated.
Anonymous User - May 4, 2003 5:59 pm:
Zope documentation started out opaque and it's only gotten foggier. Perhaps comments could be indented, small
 or on an extra column
Anonymous User - Aug. 13, 2003 4:31 am:
 Is this standard Python or a Zope extension to Python? Can't find anything related to Interface on
 www.python.org.
Anonymous User - Aug. 15, 2003 8:04 pm:
 I concur. I love Python for its economy and eloquence and would therefore love to use Zope, but the
 documentation needs to get better. Just spent 4 hours poring over it and still do not understand how I would
 start to structure my data for the company website I would like to use as a testbed. The Zope Book spends to
much time on basics and building blocks, without at single complete example. Where is the well documented and
 commented 'pet store' style app? All that comes with Zope is a one page shopping cart.

Let's take a look at this step by step. Here, you see two Python class statements. The first statement creates the interface, and the second statement creates the implementation.

Anonymous User - Dec. 5, 2001 6:46 am - In scripts you only use instances of the implementation class, in
this case HelloComponent. Perhaps it would be good for educational purposes to add an __init__ as well to
HelloComponent. Or refer to chapter 3 for the use.
Anonymous User - Dec. 12, 2001 2:57 pm - Not comment really, but question. Where I find the Interface module.
I can't with myself. Not at my filesystem nor at my ZOPE. I'd like to do practice also with this tutorial.
Anonymous User - Dec. 13, 2001 10:18 am - {ZOPEHOME}/lib/python/Interface
jshell - Jan. 24, 2002 12:56 pm - This should all be updated to reflect where interfaces are going for Zope
3. First, the interface should be named "IHello", and there should be no 'self' in the signature for the
'hello()' method.
Anonymous User - July 11, 2002 12:44 pm:
 Where can I find more info regarding Zope 3? I realize that it is a work-in-progress.
Anonymous User - Aug. 8, 2002 11:58 pm:
Get rid of the 'self' param/sig?.., yeh! This is one thing I've found distasteful in my wonderings/wanderings
thru zope. Now lets consider the double underscores. Javascript seems more elegant/simple and widespread, imo
 - it WILL be on the client...why learn both? I'd use zope 'for real' if that were the case.
Anonymous User - Sep. 13, 2002 7:12 pm:
 The reason for 'self' is so that one can distinguish between class and instance
 methods in Python.  Unlike Java, Python does not have a 'static' keyword to
 describe class methods.

The first class statement creates the Hello interface. This interface describes one method, called hello. Notice that there is no implementation for this method, interfaces do not define behavior, they just describe a specification.

The second class statement creates the HelloComponent class. This class is the actual component that does what Hello describes. This is usualy referred to as the implementation of Hello. In order for you to know what interfaces HelloComponent implements, it must somehow associate itself with an interface. The __implements__ class attribute does just that. It says, "I implement these interfaces". In this case, HelloComponent asserts that it implements one interface, Hello.

Anonymous User - Mar. 27, 2002 11:48 am - usualy -> usually

The interface describes how you would work with the object, but it doesn't dictate how that description is implemented. For example, here's a more complex implementation of the Hello interface:


import xmlrpclib
class XMLRPCHello:

    __implements__ = Hello

    def hello(self, name):
        """
        Delegates the hello call to a remote object using XML-RPC.
        """
        s = xmlrpclib.Server('http://www.zope.org/')
        return s.hello(name)

This component contacts a remote server and gets its hello greeting from a remote component.

And that's all there is to components, really. The rest of this chapter describes interfaces and how you can work with them from the perspective of components. In Chapter 3, we'll put all this together into a Zope product.

Python Interfaces

Interface describe the behavior of an object by containing useful information about the object. This information includes:

  • Prose documentation about the object. In Python terms, this is called the "doc string" of the interface. In this element, you describe how the object works in prose language and any other useful information about the object.
  • Descriptions of attributes. Attribute descriptions include the name of the attribute and prose documentation describing the attributes usage.
  • Descriptions of methods. Method descriptions can include:
    • Prose "doc string" documentation about the method and its usage.
    • A sequence of parameter objects that describes the parameters expected by the method.
  • Optional tagged data. Interface objects (and their attributes, methods, and method parameters) can have optional, application specific tagged data associated with them. Examples uses for this are security assertions, pre/post conditions, unit tests, and other possible information you may want to associate with an Interface or its attributes.

tibi - Feb. 22, 2002 5:51 am - Maybe put a link to the corresponding PEP on Python.org and say this interface
thing could be integrated into Python 2.3.

Anonymous User - Apr. 12, 2005 5:34 pm:
 For those new to interfaces: If an object is a 3D cube then its interfaces would be the 6 external 2D faces
 sorrounding it. Interfaces are the "view" of the object, what the other objects see about it. The inner cube
 can change but if the 6 sorrounding faces keep untouched the rest of the cubes (objects) will not need to
 change anything. In practice is common practice to desing the views (what we want the others to expect from
 our object) and then to implement the object itself restricted to its interfaces. Well designed interfaces
 try to be orthogonal (a face will provide the access to the object state, another face will provide the
 security of the object, another one the persistence of the object, another its graphical representation in
 the screen, ...) and the different objects will try to implement the defined set of interfaces as requested.

Anonymous User - Apr. 12, 2005 5:55 pm:
 For inte. newbies: If an object is a 3D cube then its interfaces would be the 6 external 2D faces. Ifaces.
 are the cube "view", what the other objects can see/touch. If the cube's inners change keeping constant the
 sorrounding Ifaces the other cubes/objects will need no change. In practice Ifaces are designed first in the
 time line (what we want our object to look lie), then commes the object 3D implementation. Well designed
 interfaces try to be orthogonal (one face shows the cube state, another treats the security, another shows
 its visual representation in the screen, ...). Different cubes/objects will try to implement the defined set
 of interfaces as requested.

Not all of this information is mandatory. For example, you may only want the methods of your interface to have prose documentation and not describe the arguments of the method in exact detail. Interface objects are flexible and let you give or take any of these components.

Anonymous User - Oct. 16, 2001 10:29 am - The current Interface implementation as it ships with Zope 2.4 +
does not support non-function attributes in interfaces.

Why Use Interfaces?

Interfaces solve a number of problems that arise while developing large systems with lots of developers.

  • Developers waste a lot of time looking at the source code of your system to figure out how objects work. This is even worse if someone else has already wasted their time doing the same thing.
  • Developers who are new to your system may misunderstand how your object works, causing, and possibly propagating, usage errors.
  • Because an object's interface is inferred from the source, developers may end up using methods and attributes that are meant for "internal use only".
  • Code inspection can be hard, and very discouraging to novice programmers trying to understand code written by gurus.

Interfaces try to solve these problems by providing a way for you to describe how to use an object, and a mechanism for discovering that description.

Anonymous User - Jan. 25, 2005 3:04 pm:
 Forget novices, reading code that implements interfaces turns beginers' brains into mush.

Creating Interfaces

The first step to creating a component, as you've been shown, is to create an interface.

Anonymous User - Jan. 11, 2002 3:40 pm - I'm confused as to why CORBA IDL was not mentioned/used here. I am
sure it was considered, but it would be helpful to mention why the technology was considered unsuitable in
this case. Thanks.

Interface objects can be conveniently constructed using the Python class statement. Keep in mind that this syntax can be a little misleading, because interfaces are not classes. It is important to understand that using Python's class syntax is just a convenience, and that the resulting object is an interface, not a class.

Anonymous User - Aug. 7, 2002 10:45 pm:
You might want to point out that interfaces are also known as Abstract Base Classes. This fits in better with
 the python view of things, and you do mention "concrete classes" down the road.
 You also might want to consider raising NotImplementedError exceptions in the Interface.
Anonymous User - Apr. 12, 2005 5:49 pm:
 I think the "Abstract Base Classes" is missliding since it hides the purpose of interfaces. "Base Classes"
has more to do with non interface aware language (Python/C++). I think "Abtract Base Classes" is a the way in
 which they implement Interfaces and not the opposite. Of course Python has classes and not Interfaces, but
 that's a lack in the language that pythoniers are trying to solve in an elegant way. (Dont' get me wrogn,
 Python continues to be my favourite language with or without interfaces)

To create an interface object using Python's class syntax, create a Python class that subclasses from 'Interface.Base':


from Interface import Base

class Hello(Base):

    def hello(self, name):
        """ Say hello to the world """
Anonymous User - Oct. 25, 2002 6:00 pm:
 'from Interface import Base' SHOULD BE 'from Interface import Interface'. From the __init__.py file of the
 Interface package: Base = Interface # XXX We need to stamp out Base usage.
Anonymous User - Jan. 5, 2003 8:59 am:
 Could you mention that Interface.Base is a Zope module. Im a java/c++ developer trying to adopt zope as a
platform. I would be useful to mention that Interface.Base is zope specific and not something from the python
 relm.
Anonymous User - Jan. 5, 2003 9:01 am:
 it's me again. the Word interface is used to describe constructs in some languages (like Java and virutal
 classes in C++) What could help here is a pointer back to the API guide for Interface.

This interface does not implement behavior for its methods, it just describes an interface that a typical "Hello" object would realize. By subclassing the Interface.Base interface, the resulting object Hello is an interface object. The Python interpreter confirms this:


>>> Hello
<Interface Hello at 812cbd4>

Now, you can associate the Hello Interface with your new, concrete class in which you define your user behavior. For example:


class HelloComponent:

    __implements__ = Hello

    def hello(self, name):
        return "Hello %s!" % name

This new class, HelloComponent is a concrete class that implements the Hello interface. A class can realize more than one interface. For example, say you had an interface called Item that described how an object worked as an item in a "Container" object. If you wanted to assert that HelloComponent instances realized the Item interface as well as Hello, you can provide a sequence of Interface objects to the HelloComponent class:


class HelloComponent:

    __implements__ = Hello, Item

This __implements__ attribute is called an interface assertion. An interface assertion can be either an interface, or a sequence of interface assertions. Here's a more complex example:


class Sandwich:

    __implements__ = (Food, (Nourishing, Delicious), (GetsStaleQuickly, 
                     (EdibleWithHands, GoodForLunch)))
Anonymous User - Jan. 5, 2005 9:44 am:
 I understood the first example given where the class was implementing the methods of two abstract classes. 
 e.g. 
 class Sandwich:

     __implements__= Food, GetsStaleQuickly

 however i do not understand what is meant by the different groupings with parenthesis. Are these used to
 imply a hierarchy in the relationships between the different classes??
 So can you explain whats going on in the line:
 __implements__ = (Food, (Nourishing, Delicious), (GetsStaleQuickly, 
                      (EdibleWithHands, GoodForLunch)))

 Thanks
 Tom.
Anonymous User - Jan. 5, 2005 10:01 am:
 I have been looking more at this line of code.
Am I right in assuming that it is stating for example that it is implementing methods described in Food, also
 implementing methods described in subclasses of Food :- Nourishing and Delicious etc...
 Thank 
 Tom.

Interface assertions allow complex nesting of interfaces. This is mostly useful when you wish to assert that your class implements some specific interfaces, along with whatever interfaces your base class implements:


class Sandwich(Food):

    __implements__ = (EdibleWithHands, GoodForLunch, Food.__implements__)

Take care before you assert that your class implements the interfaces of your base classes.

Anonymous User - Feb. 4, 2002 12:51 pm - What about attributes of a class? Is it possible to describe
attributes or properties of a class instead of methods only?
Anonymous User - May 21, 2002 12:11 pm:
I dont know! Languages like C++ allow you to define attributes and methods as public, however even then it is
 usually considered to be good practice to write accessor functions and methods rather than to make the
 attributes public.
Anonymous User - May 29, 2002 11:29 am:
 it seems 'interface' is the *public* part of the class *definition*, right ?

The Interface Model

Interfaces can extend other interfaces. For example, let's extend the Hello interface by adding an additional method:


class SmartHello(Hello):
    """  A Hello object that remembers who it's greeted """

    def lastGreeted(self):
        """ Returns the name of the last person greeted. """
Anonymous User - Apr. 12, 2005 6:10 pm:
 I don't think interface inheritance is a good practice. Interfaces try to declare realm behaviour so it's
 confusing (maybe even wrong) to say iface1 declares this behaviour for object implementing it while iface2
 will declares the same behaviour ¿and a bit more?. Inherintance is risky for classes and for interfaces can
 be deadly.

SmartHello extends the Hello interface. It does this by using the same syntax a class would use to subclass another class.

eradan - Mar. 4, 2002 7:12 am - You declared: "from Interface import Hello"; did you?
Anonymous User - Apr. 12, 2005 6:16 pm:
 better than
  iface1: Hello
  iface1 <- iface2:lastGreeted
  object implemens iface2

 will be:
  iface1: Hello
  iface2: logging
  object implement iface1, iface2
  (logging = lastGreeted, lastGoodbye,...)
  ifaces must be orthogonals. Don't inherit them, danger, danger!!!

Now, you can ask the SmartHello for a list of the interfaces it extends with 'getBases':


>>> SmartHello.getBases()
[<interface Hello at 80c72c8>]
Anonymous User - May 29, 2002 11:32 am:
 so, 'getBases' is a method of class *base* from 'interface' package, isn't it ?

An interface can extend any number of other interfaces, and getBases will return that list of interfaces for you. If you want to know if SmartHello extends any other interface, you could call getBases and search through the list, but a convenience method called extends is provided that returns true or false for this purpose:


>>> SmartHello.extends(Hello)
1
>>> SmartHello.extends(Sandwich)
0
>>>

Here you can see extends can be used to determine if one interface extends another.

You may notice a similarity between interfaces extending from other interfaces and classes sub-classing from other classes. This is a similar concept, but the two should not be considered equal. There is no assumption that classes and interfaces exist in a one to one relationship; one class may implement several interfaces, and a class may not implement its base classes's interfaces.

Anonymous User - Jan. 11, 2002 9:08 am - Then why use 'class' instead of 'interface' (historical/political
reasons?), especially since GvR is w Zope.com?

The distinction between a class and an interface should always be kept clear. The purpose of a class is to share the implementation of how an object works. The purpose of an interface is to document how to work with an object, not how the object is implemented. It is possible to have several different classes with very different implementations realize the same interface. Because of this, interfaces and classes should never be confused.

Anonymous User - May 29, 2002 11:35 am:
ok, so an interface is actually a class in the python meanings, but not in the Zope meaning, since it has not
 implicit implementation.. right ?
Anonymous User - May 29, 2002 11:37 am:
 well, you mean one can implement an interface without extending the actual classes tha implements this
 interface's parents & grand-parents.. is it ?

Querying an Interface

Anonymous User - Nov. 3, 2001 7:58 am - Note that there should be a description of where the Interface
package actually lives so people can try it interactively.

Interfaces can be queried for information. The simplest case is to ask an interface the names of all the various interface items it describes. From the Python interpreter, for example, you can walk right up to an interface and ask it for its names:


>>> User.names()
['getUserName', 'getFavoriteColor', 'getPassword']
Anonymous User - Nov. 18, 2002 11:39 pm:
 Where did User come from? This might be better using Hello, or SmartHello.
Anonymous User - May 8, 2004 6:59 am:
 I think the following line is missing:
 from AccessControl import User
 But I can't access User.names() anyway...
Anonymous User - Jan. 25, 2005 3:39 pm:
 I thought interfaces were to be prefixed with a capitol I?
 should it not be IUser.names()?

Interfaces can also give you more interesting information about their items. Interface objects can return a list of (name, description) tuples about their items by calling the namesAndDescriptions method.

Anonymous User - Dec. 20, 2001 2:39 pm - "[...] ask an interface the names of all the various interface items
it describes." So WTF is an "item" as used in the last sentence? An object? A class? A component? A Method or
Attribute? Please use consistent terms.
Anonymous User - Jan. 7, 2002 11:53 am - You might want to stick to the earlier introduced examples of
interfaces: Hello and SmartHello. To me it was not clear that User is a interface, too. In general, your
readers might benefit even more if this chapter would be based on a single session at the python console -
like Guido van Rossum did it in his Python Tutorial at www.python.org.

For example:


>>> User.namesAndDescriptions()
[('getUserName', <Interface.Method.Method instance at 80f38f0>),
('getFavoriteColor', <Interface.Method.Method instance at 80b24f0>),
('getPassword', <Interface.Method.Method instance at 80fded8>)]

As you can see, the "description" of the Interface's three items in these cases are all Method objects. Description objects can be either Attribute or Method objects. Attributes, methods, and interface objects implement the following interface:


'getName()' -- Returns the name of the object.

'getDoc()' -- Returns the documentation for the object.
Anonymous User - May 29, 2002 11:42 am:
 which items have implicitly these 2 methods in Hello interface ? ?

Method objects provide a way to describe rich meta-data about Python methods. Method objects have the following methods:

getSignatureInfo()
Returns a dictionary describing the method parameters.

getSignatureString()
Returns a human-readable string representation of the method's signature.

For example:


>>> m=User.namesAndDescriptions()[0][1]
>>> m
<Interface.Method.Method instance at 80f38f0>
>>> m.getSignatureString()
'(fullName=1)'
>>> m.getSignatureInfo()   
{'varargs': None, 'kwargs': None, 'optional': {'fullName': 1}, 
'required': (), 'positional': ('fullName',)}  

You can use getSignatureInfo to find out the names and types of the method parameters.

Anonymous User - May 29, 2002 11:44 am:
 i lost my way on how to fill then access this meta-data..

Checking Implementation

You can ask an interface if a certain class or instance that you hand it implements that interface. For example, say you want to know if instances of the HelloComponent class implement 'Hello':


Hello.implementedByInstancesOf(HelloComponent)
icemac - Apr. 9, 2003 9:12 am:
 now, as of Zope 2.6.1 it is:
 isImplementedByInstancesOf

This is a true expression. If you had an instance of HelloComponent, you can also ask the interface if that instance implements the interface:


Hello.implementedBy(my_hello_instance)
icemac - Apr. 9, 2003 9:13 am:
 see above:
 isImplementedBy

This would also return true if my_hello_instance was an instance of HelloComponent, or any other class that implemented the Hello Interface.

Conclusion

Interfaces provide a simple way to describe your Python objects. By using interfaces you document your objects' capabilities. As Zope becomes more component oriented, your objects will fit right in. While components and interfaces are forward looking technologies, they are useful today for documentation and verification.

Anonymous User - Aug. 9, 2002 12:23 am:
 A succinct real world example illustrating the difference between a class and interface might help. eg,
 interface 'a' is implemented by class 'b' and 'this' is why is helps me be a better zoper.

Previous Page Up one Level Next Page Components and Interfaces Comments On/Off Table of Contents