[Zodb-checkins] CVS: Zope3/src/zope/interface - advice.py:1.1.4.1 __init__.py:1.5.4.1 _flatten.py:1.5.4.1 _zope_interface_ospec.c:1.4.2.1 declarations.py:1.8.2.1 interface.py:1.9.4.1 interfaces.py:1.13.4.1 pyskel.py:1.2.28.1 type.py:1.8.4.1 _callableimplements.py:NONE implements.py:NONE

Grégoire Weber zope at i-con.ch
Sun Jun 22 11:24:17 EDT 2003


Update of /cvs-repository/Zope3/src/zope/interface
In directory cvs.zope.org:/tmp/cvs-serv24874/src/zope/interface

Modified Files:
      Tag: cw-mail-branch
	__init__.py _flatten.py _zope_interface_ospec.c 
	declarations.py interface.py interfaces.py pyskel.py type.py 
Added Files:
      Tag: cw-mail-branch
	advice.py 
Removed Files:
      Tag: cw-mail-branch
	_callableimplements.py implements.py 
Log Message:
Synced up with HEAD

=== Added File Zope3/src/zope/interface/advice.py ===
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Class advice.

This module was adapted from 'protocols.advice', part of the Python
Enterprise Application Kit (PEAK).  Please notify the PEAK authors
(pje at telecommunity.com and tsarna at sarna.org) if bugs are found or
Zope-specific changes are required, so that the PEAK version of this module
can be kept in sync.

PEAK is a Python application framework that interoperates with (but does
not require) Zope 3 and Twisted.  It provides tools for manipulating UML
models, object-relational persistence, aspect-oriented programming, and more.
Visit the PEAK home page at http://peak.telecommunity.com for more information.

$Id: advice.py,v 1.1.4.1 2003/06/22 14:23:44 gregweb Exp $
"""

from types import ClassType, FunctionType
import sys

def getFrameInfo(frame):
    """Return (kind,module,locals,globals) for a frame

    'kind' is one of "exec", "module", "class", "function call", or "unknown".
    """

    f_locals = frame.f_locals
    f_globals = frame.f_globals

    sameNamespace = f_locals is f_globals
    hasModule = '__module__' in f_locals
    hasName = '__name__' in f_globals

    sameName = hasModule and hasName
    sameName = sameName and f_globals['__name__']==f_locals['__module__']

    module = hasName and sys.modules.get(f_globals['__name__']) or None

    namespaceIsModule = module and module.__dict__ is f_globals

    if not namespaceIsModule:
        # some kind of funky exec
        kind = "exec"
    elif sameNamespace and not hasModule:
        kind = "module"
    elif sameName and not sameNamespace:
        kind = "class"
    elif not sameNamespace:
        kind = "function call"
    else:
        # How can you have f_locals is f_globals, and have '__module__' set?
        # This is probably module-level code, but with a '__module__' variable.
        kind = "unknown"
    return kind, module, f_locals, f_globals


def addClassAdvisor(callback, depth=2):
    """Set up 'callback' to be passed the containing class upon creation

    This function is designed to be called by an "advising" function executed
    in a class suite.  The "advising" function supplies a callback that it
    wishes to have executed when the containing class is created.  The
    callback will be given one argument: the newly created containing class.
    The return value of the callback will be used in place of the class, so
    the callback should return the input if it does not wish to replace the
    class.

    The optional 'depth' argument to this function determines the number of
    frames between this function and the targeted class suite.  'depth'
    defaults to 2, since this skips this function's frame and one calling
    function frame.  If you use this function from a function called directly
    in the class suite, the default will be correct, otherwise you will need
    to determine the correct depth yourself.

    This function works by installing a special class factory function in
    place of the '__metaclass__' of the containing class.  Therefore, only
    callbacks *after* the last '__metaclass__' assignment in the containing
    class will be executed.  Be sure that classes using "advising" functions
    declare any '__metaclass__' *first*, to ensure all callbacks are run."""

    frame = sys._getframe(depth)
    kind, module, caller_locals, caller_globals = getFrameInfo(frame)

    # This causes a problem when zope interfaces are used from doctest.
    # In these cases, kind == "exec".
    #
    #if kind != "class":
    #    raise SyntaxError(
    #        "Advice must be in the body of a class statement"
    #    )

    previousMetaclass = caller_locals.get('__metaclass__')
    defaultMetaclass  = caller_globals.get('__metaclass__', ClassType)


    def advise(name, bases, cdict):

        if '__metaclass__' in cdict:
            del cdict['__metaclass__']

        if previousMetaclass is None:
             if bases:
                 # find best metaclass or use global __metaclass__ if no bases
                 meta = determineMetaclass(bases)
             else:
                 meta = defaultMetaclass

        elif isClassAdvisor(previousMetaclass):
            # special case: we can't compute the "true" metaclass here,
            # so we need to invoke the previous metaclass and let it
            # figure it out for us (and apply its own advice in the process)
            meta = previousMetaclass

        else:
            meta = determineMetaclass(bases, previousMetaclass)

        newClass = meta(name,bases,cdict)

        # this lets the callback replace the class completely, if it wants to
        return callback(newClass)

    # introspection data only, not used by inner function
    advise.previousMetaclass = previousMetaclass
    advise.callback = callback

    # install the advisor
    caller_locals['__metaclass__'] = advise


def isClassAdvisor(ob):
    """True if 'ob' is a class advisor function"""
    return isinstance(ob,FunctionType) and hasattr(ob,'previousMetaclass')


def determineMetaclass(bases, explicit_mc=None):
    """Determine metaclass from 1+ bases and optional explicit __metaclass__"""

    meta = [getattr(b,'__class__',type(b)) for b in bases]

    if explicit_mc is not None:
        # The explicit metaclass needs to be verified for compatibility
        # as well, and allowed to resolve the incompatible bases, if any
        meta.append(explicit_mc)

    if len(meta)==1:
        # easy case
        return meta[0]

    candidates = minimalBases(meta) # minimal set of metaclasses

    if not candidates:
        # they're all "classic" classes
        return ClassType

    elif len(candidates)>1:
        # We could auto-combine, but for now we won't...
        raise TypeError("Incompatible metatypes",bases)

    # Just one, return it
    return candidates[0]


def minimalBases(classes):
    """Reduce a list of base classes to its ordered minimum equivalent"""

    classes = [c for c in classes if c is not ClassType]
    candidates = []

    for m in classes:
        for n in classes:
            if issubclass(n,m) and m is not n:
                break
        else:
            # m has no subclasses in 'classes'
            if m in candidates:
                candidates.remove(m)    # ensure that we're later in the list
            candidates.append(m)

    return candidates



=== Zope3/src/zope/interface/__init__.py 1.5 => 1.5.4.1 ===
--- Zope3/src/zope/interface/__init__.py:1.5	Sat May  3 12:34:46 2003
+++ Zope3/src/zope/interface/__init__.py	Sun Jun 22 10:23:44 2003
@@ -78,14 +78,17 @@
 
 from zope.interface.interface import Attribute
 
-import zope.interface.implements
-from zope.interface._callableimplements import hookup
-hookup()
-del hookup
-
 from zope.interface.declarations import providedBy, implementedBy
 from zope.interface.declarations import classImplements, classImplementsOnly
 from zope.interface.declarations import directlyProvidedBy, directlyProvides
 from zope.interface.declarations import implements, implementsOnly
 from zope.interface.declarations import classProvides, moduleProvides
-from zope.interface.declarations import InterfaceSpecification
+from zope.interface.declarations import InterfaceSpecification, Spec
+
+# The following are to make spec pickles cleaner
+from zope.interface.declarations import Implements, Only, Provides
+
+
+from zope.interface.interfaces import IInterfaceDeclaration
+moduleProvides(IInterfaceDeclaration)
+__all__ = ('Interface', 'Attribute') + tuple(IInterfaceDeclaration)


=== Zope3/src/zope/interface/_flatten.py 1.5 => 1.5.4.1 ===
--- Zope3/src/zope/interface/_flatten.py:1.5	Sat May  3 12:35:29 2003
+++ Zope3/src/zope/interface/_flatten.py	Sun Jun 22 10:23:44 2003
@@ -19,7 +19,7 @@
 """
 __metaclass__ = type # All classes are new style when run with Python 2.2+
 
-from zope.interface import Interface, InterfaceSpecification
+from zope.interface import InterfaceSpecification
 
 def _flatten(implements, include_None=0):
 


=== Zope3/src/zope/interface/_zope_interface_ospec.c 1.4 => 1.4.2.1 ===
--- Zope3/src/zope/interface/_zope_interface_ospec.c:1.4	Wed May 21 14:21:40 2003
+++ Zope3/src/zope/interface/_zope_interface_ospec.c	Sun Jun 22 10:23:44 2003
@@ -17,8 +17,10 @@
 #include "structmember.h"
 
 static PyObject *str___provides__, *str___implements__, *str___class__;
-static PyObject *str___dict__, *str___signature__;
+static PyObject *str___dict__, *str___signature__, *str_flattened;
 static PyObject *_implements_reg, *classImplements, *proxySig, *oldSpecSig;
+static PyObject *combinedSpec, *str_extends, *declarations;
+static PyObject *str___providedBy__, *str_only;
 
 #define TYPE(O) ((PyTypeObject*)(O))
 #define OBJECT(O) ((PyObject*)(O))
@@ -67,7 +69,9 @@
         /* tp_getattro       */ (getattrofunc)0,
         /* tp_setattro       */ (setattrofunc)0,
         /* tp_as_buffer      */ 0,
-        /* tp_flags          */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
+        /* tp_flags          */ Py_TPFLAGS_DEFAULT 
+                                | Py_TPFLAGS_BASETYPE
+                                ,
 	/* tp_doc            */ ISBtype__doc__,
         /* tp_traverse       */ (traverseproc)0,
         /* tp_clear          */ (inquiry)0,
@@ -90,43 +94,58 @@
 
 typedef struct {
   PyObject_HEAD
-  PyObject *ob;
+  PyObject *provides;
+  PyObject *cls;
+  PyObject *spec;
 } OSpec;
 
-static PyObject *
+static PyTypeObject OSpecType;
+
+static int
 OSpec_init(OSpec *self, PyObject *args, PyObject *kwds)
 {
-	static char *kwlist[] = {"ob", NULL};
-        PyObject *ob;
+	static char *kwlist[] = {"provides", "cls", NULL};
+        PyObject *provides, *cls;
 
-        if (! PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, 
-                                          &ob))
-        	return NULL; 
+        if (! PyArg_ParseTupleAndKeywords(args, kwds, "OO", kwlist, 
+                                          &provides, &cls))
+        	return -1; 
+
+        Py_INCREF(provides);
+        self->provides = provides;
+        Py_INCREF(cls);
+        self->cls = cls;
 
-        Py_INCREF(ob);
-        self->ob = ob;
-
-    	Py_INCREF(Py_None);
-    	return Py_None;
+        return 0;
 }
 
-static void
-OSpec_dealloc(OSpec *self)
+static int
+OSpec_traverse(OSpec *self, visitproc visit, void *arg)
 {
-  Py_XDECREF(self->ob);
-  self->ob_type->tp_free((PyObject*)self);
+  if (self->provides != Py_None && visit(self->provides, arg) < 0)
+    return -1;
+  if (visit(self->cls, arg) < 0)
+    return -1;
+  if (self->spec && visit(self->spec, arg) < 0)
+    return -1;
+  return 0;
 }
 
-static PyObject *
-OSpec_getob(OSpec *self, void *closure)
+static int
+OSpec_clear(OSpec *self)
 {
-  if (self->ob == NULL) {
-    PyErr_SetString(PyExc_AttributeError, "No ob attribute set");
-    return NULL;
-  }
+  Py_XDECREF(self->provides);
+  Py_XDECREF(self->cls);
+  Py_XDECREF(self->spec);
+  return 0;
+}
 
-  Py_INCREF(self->ob);
-  return self->ob;
+static void
+OSpec_dealloc(OSpec *self)
+{
+  PyObject_GC_UnTrack((PyObject *) self);
+  OSpec_clear(self);
+  self->ob_type->tp_free((PyObject*)self);
 }
 
 static PyObject *
@@ -168,31 +187,17 @@
 {
   PyObject *provides, *psig=0, *cls, *key, *dict, *implements, *sig=0, *result;
 
-  if (self->ob == NULL) {
-    PyErr_SetString(PyExc_AttributeError, "No ob attribute set");
-    return NULL;
-  }
-
-  provides = PyObject_GetAttr(self->ob, str___provides__);
-  if (provides == NULL)
-    PyErr_Clear();
-  else 
+  provides = self->provides;
+  if (provides != Py_None)
     {
       psig = getsig(provides, NULL);
-      Py_DECREF(provides);
       if (psig == NULL)
         return NULL;
     }
 
   /* Own: psig */
 
-  /* Whimper. We have to do a getattr, because ob may be a proxy */
-  cls = PyObject_GetAttr(self->ob, str___class__);
-  if (cls == NULL)
-    {
-      PyErr_Clear();
-      goto done;
-    }
+  cls = self->cls;
 
   /* Own: psig, cls */
 
@@ -221,7 +226,7 @@
   else
     dict = PyObject_GetAttr(cls, str___dict__);
 
-  /* Own: psig, cls, dict */
+  /* Own: psig, dict */
 
   if (dict == NULL)
     {
@@ -255,9 +260,6 @@
       Py_DECREF(dict);
     }
 
-  Py_DECREF(cls);
-
-
   /* Own: psig */
 
 
@@ -267,11 +269,14 @@
       return NULL;
     }
 
- done:
-  if (sig == Py_None && psig != NULL)
+  if (psig != NULL && ! PyObject_IsTrue(psig))
+    {
+      Py_DECREF(psig);
+      psig = NULL;
+    }
+
+  if (sig != NULL && ! PyObject_IsTrue(sig))
     {
-      /* We have a provided sig, but the class sig was None, so make class
-         sig NULL  */
       Py_DECREF(sig);
       sig = NULL;
     }
@@ -295,17 +300,10 @@
   else if (psig != NULL)
     return psig;
   else
-    {
-      Py_INCREF(Py_None);
-      return Py_None;
-    }
+    return PyString_FromString("");
 }    
 
 static PyGetSetDef OSpec_getset[] = {
-    {"ob", 
-     (getter)OSpec_getob, (setter)0,
-     "Subject of the object specification",
-     NULL},
     {"__signature__", 
      (getter)OSpec_getsig, (setter)0,
      "Specification signature",
@@ -313,7 +311,141 @@
     {NULL}  /* Sentinel */
 };
 
+static PyObject *
+getspec(OSpec *self)
+{
+  if (self->spec == NULL)
+    self->spec = PyObject_CallFunctionObjArgs(combinedSpec, 
+                                              self->provides, self->cls,
+                                              NULL);
+  return self->spec;
+}
 
+static PyObject *
+OSpec_add(PyObject *v, PyObject *w)
+{
+  if (PyObject_TypeCheck(v, &OSpecType))
+    {
+      v = getspec((OSpec*)v);
+      if (v == NULL) 
+        return NULL;
+    }
+  else if (PyObject_TypeCheck(w, &OSpecType))
+    {
+      w = getspec((OSpec*)w);
+      if (w == NULL) 
+        return NULL;
+    }
+  else
+    {
+      PyErr_SetString(PyExc_TypeError, "Invalid types for add");
+    }
+
+  return PyNumber_Add(v, w);
+}
+
+static PyObject *
+OSpec_sub(PyObject *v, PyObject *w)
+{
+  if (PyObject_TypeCheck(v, &OSpecType))
+    {
+      v = getspec((OSpec*)v);
+      if (v == NULL) 
+        return NULL;
+    }
+  else if (PyObject_TypeCheck(w, &OSpecType))
+    {
+      w = getspec((OSpec*)w);
+      if (w == NULL) 
+        return NULL;
+    }
+  else
+    {
+      PyErr_SetString(PyExc_TypeError, "Invalid types for subtract");
+    }
+
+  return PyNumber_Subtract(v, w);
+}
+
+static int
+OSpec_nonzero(OSpec *self)
+{
+  return PyObject_IsTrue(getspec(self));
+}
+
+static PyNumberMethods OSpec_as_number = {
+    /* nb_add                  */ (binaryfunc)OSpec_add,
+    /* nb_subtract             */ (binaryfunc)OSpec_sub,
+    /* nb_multiply to nb_absolute */ 0, 0, 0, 0, 0, 0, 0, 0, 
+    /* nb_nonzero             */ (inquiry)OSpec_nonzero,
+};
+
+static int
+OSpec_contains(OSpec *self, PyObject *v)
+{
+  PyObject *spec;
+
+  spec = getspec(self);
+  if (spec == NULL)
+    return -1;
+
+  return PySequence_In(spec, v);
+}
+
+
+static PySequenceMethods OSpec_as_sequence = {
+	/* sq_length         */ 0,
+	/* sq_concat         */ 0,
+	/* sq_repeat         */ 0,
+	/* sq_item           */ 0,
+	/* sq_slice          */ 0,
+	/* sq_ass_item       */ 0,
+	/* sq_ass_slice      */ 0,
+	/* sq_contains       */ (objobjproc)OSpec_contains,
+};
+
+static PyObject *
+OSpec_iter(OSpec *self)
+{
+  PyObject *spec;
+
+  spec = getspec(self);
+  if (spec == NULL)
+    return NULL;
+
+  return PyObject_GetIter(spec);
+}
+
+static PyObject *
+OSpec_flattened(OSpec *self)
+{
+  PyObject *spec;
+
+  spec = getspec(self);
+  if (spec == NULL)
+    return NULL;
+
+  return PyObject_CallMethodObjArgs(spec, str_flattened, NULL);
+}
+
+static PyObject *
+OSpec_extends(OSpec *self, PyObject *other)
+{
+  PyObject *spec;
+
+  spec = getspec(self);
+  if (spec == NULL)
+    return NULL;
+
+  return PyObject_CallMethodObjArgs(spec, str_extends, other, NULL);
+}
+
+
+static struct PyMethodDef OSpec_methods[] = {
+	{"flattened",	(PyCFunction)OSpec_flattened,	METH_NOARGS, ""},
+	{"extends",	(PyCFunction)OSpec_extends,	METH_O, ""},
+	{NULL,		NULL}		/* sentinel */
+};
 
 
 static char OSpecType__doc__[] = 
@@ -324,7 +456,7 @@
 	PyObject_HEAD_INIT(NULL)
 	/* ob_size           */ 0,
 	/* tp_name           */ "zope.interface._zope_interface_ospec."
-                                "ObjectSpecificationBase",
+                                "ObjectSpecification",
 	/* tp_basicsize      */ sizeof(OSpec),
 	/* tp_itemsize       */ 0,
 	/* tp_dealloc        */ (destructor)OSpec_dealloc,
@@ -333,8 +465,8 @@
 	/* tp_setattr        */ (setattrfunc)0,
 	/* tp_compare        */ (cmpfunc)0,
 	/* tp_repr           */ (reprfunc)0,
-	/* tp_as_number      */ 0,
-	/* tp_as_sequence    */ 0,
+	/* tp_as_number      */ &OSpec_as_number,
+	/* tp_as_sequence    */ &OSpec_as_sequence,
 	/* tp_as_mapping     */ 0,
 	/* tp_hash           */ (hashfunc)0,
 	/* tp_call           */ (ternaryfunc)0,
@@ -342,15 +474,19 @@
         /* tp_getattro       */ (getattrofunc)0,
         /* tp_setattro       */ (setattrofunc)0,
         /* tp_as_buffer      */ 0,
-        /* tp_flags          */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
+        /* tp_flags          */ Py_TPFLAGS_DEFAULT
+                                | Py_TPFLAGS_BASETYPE
+                                | Py_TPFLAGS_CHECKTYPES
+                                | Py_TPFLAGS_HAVE_GC
+                                ,
 	/* tp_doc            */ OSpecType__doc__,
-        /* tp_traverse       */ (traverseproc)0,
-        /* tp_clear          */ (inquiry)0,
+        /* tp_traverse       */ (traverseproc)OSpec_traverse,
+        /* tp_clear          */ (inquiry)OSpec_clear,
         /* tp_richcompare    */ (richcmpfunc)0,
         /* tp_weaklistoffset */ (long)0,
-        /* tp_iter           */ (getiterfunc)0,
+        /* tp_iter           */ (getiterfunc)OSpec_iter,
         /* tp_iternext       */ (iternextfunc)0,
-        /* tp_methods        */ 0,
+        /* tp_methods        */ OSpec_methods,
         /* tp_members        */ 0,
         /* tp_getset         */ OSpec_getset,
         /* tp_base           */ 0,
@@ -363,93 +499,251 @@
         /* tp_new            */ (newfunc)0 /*PyType_GenericNew*/,
 };
 
-/* List of methods defined in the module */
+static PyObject *
+getObjectSpecification(PyObject *ignored, PyObject *ob)
+{
+  PyObject *provides, *cls, *result;
+  static PyObject *empty = NULL;
 
-static struct PyMethodDef module_methods[] = {
+  provides = PyObject_GetAttr(ob, str___provides__);
+  if (provides == NULL)
+    PyErr_Clear();
 
-	{NULL,	 (PyCFunction)NULL, 0, NULL}		/* sentinel */
-};
+  cls = PyObject_GetAttr(ob, str___class__);
+  if (cls == NULL)
+    {
+      PyErr_Clear();
+      if (provides == NULL)
+        {
+          if (empty == NULL)
+            {
+              empty = PyObject_GetAttrString(declarations, "_empty");
+              if (empty == NULL)
+                return NULL;
+            }
+          Py_INCREF(empty);
+          return empty;
+        }
+      return provides;
+    }
 
+  if (provides == NULL)
+    {
+      Py_INCREF(Py_None);
+      provides = Py_None;
+    }
+  
+  result = PyObject_CallFunctionObjArgs(OBJECT(&OSpecType), provides, cls, 
+                                        NULL);
+  Py_DECREF(provides);
+  Py_DECREF(cls);
 
-static char _zope_interface_ospec_module_documentation[] = 
-""
-;
+  return result;
+}
 
-#ifndef PyMODINIT_FUNC	/* declarations for DLL import/export */
-#define PyMODINIT_FUNC void
-#endif
-PyMODINIT_FUNC
-init_zope_interface_ospec(void)
+static PyObject *
+providedBy(PyObject *ignored, PyObject *ob)
 {
-  PyObject *module;
+  PyObject *result;
   
+  result = PyObject_GetAttr(ob, str___providedBy__);
+  if (result != NULL)
+    {
+      /* We want to make sure we have a spec. We can't do a type check
+         because we may have a proxy, so we'll just try to get the
+         only attribute.
+      */
+      ignored = PyObject_GetAttr(result, str_only);
+      if (ignored == NULL)
+        PyErr_Clear();
+      else
+        {
+          Py_DECREF(ignored);
+          return result;
+        }
+    }
+
+  PyErr_Clear();
+
+  return getObjectSpecification(NULL, ob);
+}
+
+typedef struct {
+  PyObject_HEAD
+} OSpecDescr;
+
+static PyObject *
+OSpecDescr_descr_get(PyObject *self, PyObject *inst, PyObject *cls)
+{
+  if (inst == NULL)
+    inst = cls;
+
+  return getObjectSpecification(NULL, inst);
+}
+
+static PyTypeObject OSpecDescrType = {
+	PyObject_HEAD_INIT(NULL)
+	/* ob_size           */ 0,
+	/* tp_name           */ "zope.interface._zope_interface_ospec."
+                                "ObjectSpecificationDescriptor",
+	/* tp_basicsize      */ sizeof(OSpecDescr),
+	
+        /* tp_itemsize to tp_as_buffer */ 
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+
+        /* tp_flags          */ Py_TPFLAGS_DEFAULT
+				| Py_TPFLAGS_BASETYPE ,
+	/* tp_doc            */ "ObjectSpecification descriptor",
+        
+        /* tp_traverse to tp_dict */
+        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+
+        /* tp_descr_get      */ (descrgetfunc)OSpecDescr_descr_get,
+};
+
+int
+init_globals(void)
+{
   str___implements__ = PyString_FromString("__implements__");
   if (str___implements__ == NULL)
-    return;
+    return -1;
   
   str___provides__ = PyString_FromString("__provides__");
   if (str___provides__ == NULL)
-    return;
+    return -1;
+  
+  str___providedBy__ = PyString_FromString("__providedBy__");
+  if (str___providedBy__ == NULL)
+    return -1;
   
   str___class__ = PyString_FromString("__class__");
   if (str___class__ == NULL)
-    return;
+    return -1;
   
   str___dict__ = PyString_FromString("__dict__");
   if (str___dict__ == NULL)
-    return;
+    return -1;
   
   str___signature__ = PyString_FromString("__signature__");
   if (str___signature__ == NULL)
-    return;
+    return -1;
+  
+  str_flattened = PyString_FromString("flattened");
+  if (str_flattened == NULL)
+    return -1;
+  
+  str_extends = PyString_FromString("extends");
+  if (str_extends == NULL)
+    return -1;
+  
+  str_only = PyString_FromString("only");
+  if (str_only == NULL)
+    return -1;
   
   _implements_reg = PyDict_New();
   if (_implements_reg == NULL)
-    return;
+    return -1;
 
-  module = PyImport_ImportModule("zope.interface.declarations");
-  if (module == NULL) 
-    return;
+  return 0;
+}
 
-  classImplements = PyObject_GetAttrString(module, "classImplements");
+int
+init_declarations(void)
+{
+  declarations = PyImport_ImportModule("zope.interface.declarations");
+  if (declarations == NULL)
+    return -1;
+
+  classImplements = PyObject_GetAttrString(declarations, "classImplements");
   if (classImplements == NULL)
-    return;
+    return -1;
 
-  proxySig = PyObject_GetAttrString(module, "proxySig");
+  proxySig = PyObject_GetAttrString(declarations, "proxySig");
   if (proxySig == NULL)
-    return;
+    return -1;
 
-  oldSpecSig = PyObject_GetAttrString(module, "oldSpecSig");
+  oldSpecSig = PyObject_GetAttrString(declarations, "oldSpecSig");
   if (oldSpecSig == NULL)
-    return;
+    return -1;
+
+  combinedSpec = PyObject_GetAttrString(declarations, "combinedSpec");
+  if (combinedSpec == NULL)
+    return -1;
+  return 0;
+}
+
+static struct PyMethodDef module_methods[] = {
+	{"getObjectSpecification",  (PyCFunction)getObjectSpecification,
+         METH_O, "internal function to compute an object spec"},
+	{"providedBy",  (PyCFunction)providedBy, METH_O, 
+         "Return a specification for the interfaces of an object"},
+	{NULL,	 (PyCFunction)NULL, 0, NULL}		/* sentinel */
+};
+
+static char _zope_interface_ospec_module_documentation[] = 
+"C implementation of parts of zope.interface.declarations"
+;
+
+#ifndef PyMODINIT_FUNC	/* declarations for DLL import/export */
+#define PyMODINIT_FUNC void
+#endif
+PyMODINIT_FUNC
+init_zope_interface_ospec(void)
+{
+  PyObject *module;
 
-  Py_DECREF(module);
- 
-  OSpecType.tp_new = PyType_GenericNew;
-  ISBType.tp_new = PyType_GenericNew;
-  
   /* Initialize types: */  
+
+  ISBType.tp_new = PyType_GenericNew;
   if (PyType_Ready(&ISBType) < 0)
     return;
+
+
+  OSpecType.tp_new = PyType_GenericNew;
+  OSpecType.tp_free = _PyObject_GC_Del;
   if (PyType_Ready(&OSpecType) < 0)
     return;
+  if (OSpecType.tp_dict && 
+      PyMapping_SetItemString(OSpecType.tp_dict, "only", Py_True) < 0
+      )
+    return;
 
+ 
+  OSpecDescrType.tp_new = PyType_GenericNew;
+  if (PyType_Ready(&OSpecDescrType) < 0)
+    return;
 
+  if (init_globals() < 0)
+    return;
+  
   /* Create the module and add the functions */
   module = Py_InitModule3("_zope_interface_ospec", module_methods,
                           _zope_interface_ospec_module_documentation);
   
   if (module == NULL)
     return;
-  
+
   /* Add types: */
   if (PyModule_AddObject(module, "InterfaceSpecificationBase", 
                          (PyObject *)&ISBType) < 0)
     return;
-  if (PyModule_AddObject(module, "ObjectSpecificationBase", 
+
+  if (PyModule_AddObject(module, "ObjectSpecification", 
                          (PyObject *)&OSpecType) < 0)
     return;
+
+  if (PyModule_AddObject(module, "ObjectSpecificationDescriptor", 
+                         (PyObject *)&OSpecDescrType) < 0)
+    return;
+
   if (PyModule_AddObject(module, "_implements_reg", _implements_reg) < 0)
     return;
+
+  /* init_declarations() loads objects from zope.interface.declarations,
+     which circularly depends on the objects defined in this module.
+     Call init_declarations() last to ensure that the necessary names
+     are bound.
+  */
+  init_declarations();
 }
 


=== Zope3/src/zope/interface/declarations.py 1.8 => 1.8.2.1 ===
--- Zope3/src/zope/interface/declarations.py:1.8	Wed May 21 13:26:39 2003
+++ Zope3/src/zope/interface/declarations.py	Sun Jun 22 10:23:44 2003
@@ -18,6 +18,7 @@
 from zope.interface.interface import InterfaceClass, mergeOrderings
 import exceptions
 from types import ClassType
+from zope.interface.advice import addClassAdvisor
 
 # There are imports from _zope_interface_ospec later in the file
 # because _zope_interface_ospec depends on some functions defined
@@ -141,68 +142,168 @@
 # This function is needed by _zope_interface_ospec and, so, must be
 # defined before _zope_interface_ospec is imported.
 def oldSpecSig(cls, implements):
-    implements = OnlyImplementsSpecification(implements)
+    implements = ImplementsOnlySpecification(implements)
     _setImplements(cls, implements)
     return implements.__signature__
 
 # This is overridden by _zope_interface_ospec.
-class ObjectSpecificationBase:
 
-    __slots__ = ['ob']
+def combinedSpec(provides, cls):
+    if provides is not None:
+        result = [provides]
+    else:
+        result = []
+
+    _gatherSpecs(cls, result)
+
+    return InterfaceSpecification(*result)
+
+class ObjectSpecification_py:
+    """Provide object specifications
+
+    These combine information for the object and for it's classes.
 
-    def __init__(self, ob):
-        self.ob = ob
+    For example::
+
+        >>> from zope.interface import Interface
+        >>> class I1(Interface): pass
+        ...
+        >>> class I2(Interface): pass
+        ...
+        >>> class I3(Interface): pass
+        ...
+        >>> class I31(I3): pass
+        ...
+        >>> class I4(Interface): pass
+        ...
+        >>> class I5(Interface): pass
+        ...
+        >>> class A: implements(I1)
+        ...
+        >>> class B: __implements__ = I2
+        ...
+        >>> class C(A, B): implements(I31)
+        ...
+        >>> c = C()
+        >>> directlyProvides(c, I4)
+        >>> [i.__name__ for i in providedBy(c)]
+        ['I4', 'I31', 'I1', 'I2']
+        >>> [i.__name__ for i in providedBy(c).flattened()]
+        ['I4', 'I31', 'I3', 'I1', 'I2', 'Interface']
+        >>> int(I1 in providedBy(c))
+        1
+        >>> int(I3 in providedBy(c))
+        0
+        >>> int(providedBy(c).extends(I3))
+        1
+        >>> int(providedBy(c).extends(I31))
+        1
+        >>> int(providedBy(c).extends(I5))
+        0
+        >>> class COnly(A, B): implementsOnly(I31)
+        ...
+        >>> class D(COnly): implements(I5)
+        ...
+        >>> c = D()
+        >>> directlyProvides(c, I4)
+        >>> [i.__name__ for i in providedBy(c)]
+        ['I4', 'I5', 'I31']
+        >>> [i.__name__ for i in providedBy(c).flattened()]
+        ['I4', 'I5', 'I31', 'I3', 'Interface']
+        >>> int(I1 in providedBy(c))
+        0
+        >>> int(I3 in providedBy(c))
+        0
+        >>> int(providedBy(c).extends(I3))
+        1
+        >>> int(providedBy(c).extends(I1))
+        0
+        >>> int(providedBy(c).extends(I31))
+        1
+        >>> int(providedBy(c).extends(I5))
+        1
+    """
+
+    __slots__ = ['provides', 'cls', '_specslot']
+
+    only = True
+
+    def __init__(self, provides, cls):
+        self.provides = provides
+        self.cls = cls
+
+    def __nonzero__(self):
+        """
+        >>> from zope.interface import Interface
+        >>> class I1(Interface):
+        ...     pass
+        >>> class I2(Interface):
+        ...     pass
+        >>> class C:
+        ...     implements(I1)
+        >>> c = C()
+        >>> int(bool(providedBy(c)))
+        1
+        >>> directlyProvides(c, I2)
+        >>> int(bool(providedBy(c)))
+        1
+        >>> class C:
+        ...     pass
+        >>> c = C()
+        >>> int(bool(providedBy(c)))
+        0
+        >>> directlyProvides(c, I2)
+        >>> int(bool(providedBy(c)))
+        1
+        """
+        return bool(self.__signature__)
 
     def __signature__(self):
-        ob = self.ob
 
-        provides = getattr(ob, '__provides__', None)
+        provides = self.provides
         if provides is not None:
             provides = provides.__signature__
         else:
             provides = ''
-        sig = ''
 
+
+        sig = ''
+        cls = self.cls
         try:
-            cls = ob.__class__
+            flags = cls.__flags__
         except AttributeError:
-            # If there's no class, we'll just use the instance spec
-            pass
-        else:
+            flags = heap
 
+        if flags & heap:
             try:
-                flags = cls.__flags__
+                dict = cls.__dict__
             except AttributeError:
-                flags = heap
+                sig = proxySig(cls)
+
+            else:
+                # Normal case
+                implements = dict.get('__implements__')
+                if implements is None:
+                    # No implements spec, lets add one:
+                    classImplements(cls)
+                    implements = dict['__implements__']
 
-            if flags & heap:
                 try:
-                    dict = cls.__dict__
+                    sig = implements.__signature__
                 except AttributeError:
-                    sig = proxySig(cls)
+                    # Old-style implements!  Fix it up.
+                    sig = oldSpecSig(cls, implements)
+
+        else:
+            # Look in reg
+            implements = _implements_reg.get(cls)
+            if implements is None:
+                # No implements spec, lets add one:
+                classImplements(cls)
+                implements = _implements_reg[cls]
+            sig = implements.__signature__
 
-                else:
-                    # Normal case
-                    implements = dict.get('__implements__')
-                    if implements is None:
-                        # No implements spec, lets add one:
-                        classImplements(cls)
-                        implements = dict['__implements__']
-
-                    try:
-                        sig = implements.__signature__
-                    except AttributeError:
-                        # Old-style implements!  Fix it up.
-                        sig = oldSpecSig(cls, implements)
 
-            else:
-                # Look in reg
-                implements = _implements_reg.get(cls)
-                if implements is None:
-                        # No implements spec, lets add one:
-                        classImplements(cls)
-                        implements = _implements_reg[cls]
-                sig = implements.__signature__
 
         if sig:
             if provides:
@@ -213,12 +314,114 @@
 
     __signature__ = property(__signature__)
 
+    def _v_spec(self):
+        spec = getattr(self, '_specslot', self)
+        if spec is not self:
+            return spec
+
+        spec = combinedSpec(self.provides, self.cls)
+
+        self._specslot = spec
+
+        return spec
+
+    _v_spec = property(_v_spec)
+
+    def __contains__(self, interface):
+        return interface in self._v_spec
+
+    def __iter__(self):
+        return iter(self._v_spec)
+
+    def flattened(self):
+        return self._v_spec.flattened()
+
+    def extends(self, interface):
+        return self._v_spec.extends(interface)
+
+    def __add__(self, other):
+        return self._v_spec + other
+    __radd__ = __add__
+
+    def __sub__(self, other):
+        return self._v_spec - other
+
+# We keep ObjectSpecification_py around for doctest. :)
+ObjectSpecification = ObjectSpecification_py
+
+def getObjectSpecification(ob):
+
+    provides = getattr(ob, '__provides__', None)
+    try:
+        cls = ob.__class__
+    except AttributeError:
+        # We can't get the class, so just consider provides
+        if provides is not None:
+            # Just use the provides spec
+            return provides
+
+        # No interfaces
+        return _empty
+
+    return ObjectSpecification(provides, cls)
+
+def providedBy(ob):
+
+    # Here we have either a special object, an old-style declaration
+    # or a descriptor
+
+    try:
+        r = ob.__providedBy__
+
+        # We might have gotten a descriptor from an instance of a
+        # class (like an ExtensionClass) that doesn't support
+        # descriptors.  We'll make sure we got one by trying to get
+        # the only attribute, which all specs have.
+        r.only
+
+    except AttributeError:
+        # No descriptor, so fall back to a plain object spec
+        r = getObjectSpecification(ob)
+
+    return r
+
+class ObjectSpecificationDescriptor:
+
+    def __get__(self, inst, cls):
+        """Get an object specification for an object
+
+        For example::
+
+          >>> from zope.interface import Interface
+          >>> class IFoo(Interface): pass
+          ...
+          >>> class IFooFactory(Interface): pass
+          ...
+          >>> class C:
+          ...   implements(IFoo)
+          ...   classProvides(IFooFactory)
+          >>> [i.__name__ for i in C.__providedBy__]
+          ['IFooFactory']
+          >>> [i.__name__ for i in C().__providedBy__]
+          ['IFoo']
+
+        """
+
+        # Get an ObjectSpecification bound to either an instance or a class,
+        # depending on how we were accessed.
+        
+        if inst is None:
+            return getObjectSpecification(cls)
+        else:
+            return getObjectSpecification(inst)
+
 from _zope_interface_ospec import _implements_reg
 from _zope_interface_ospec import InterfaceSpecificationBase
-from _zope_interface_ospec import ObjectSpecificationBase
-
+from _zope_interface_ospec import ObjectSpecification
+from _zope_interface_ospec import getObjectSpecification, providedBy
+from _zope_interface_ospec import ObjectSpecificationDescriptor
 
-class InterfaceSpecification(InterfaceSpecificationBase):
+def InterfaceSpecification(*interfaces):
     """Create an interface specification
 
     The arguments are one or more interfaces or interface
@@ -227,39 +430,48 @@
     A new interface specification (IInterfaceSpecification) with
     the given interfaces is returned.
     """
+    return Spec(*_flattenSpecs(interfaces, []))
+
+
+_spec_cache = {}
+
+class Spec(InterfaceSpecificationBase):
 
     only = False
 
-    def __init__(self, *interfaces):
-        self.interfaces = tuple(_flattenSpecs(interfaces, []))
-        set = {}
-        iro = mergeOrderings(
-            [iface.__iro__ for iface in self.interfaces],
-            set)
-        self.__iro__ = iro
-        self.set = set
+    # We don't want to pickle these
+    def __reduce__(self):
+        raise TypeError, "can't pickle InterfaceSpecification objects"
 
-        self._computeSignature(iro)
+    def __init__(self, *interfaces):
+        self.interfaces = interfaces
 
-    def _computeSignature(self, iro):
-        """Compute a specification signature
+        cached = _spec_cache.get(interfaces)
+        if not cached:
+            set = {}
+            iro = mergeOrderings(
+                [iface.__iro__ for iface in self.interfaces],
+                set)
+            sig = '\t'.join([iface.__identifier__ for iface in iro])
+            cached = iro, set, sig
+            _spec_cache[interfaces] = cached
 
-        For example::
+        self.__iro__, self.set, self.__signature__ = cached
 
-          >>> from zope.interface import Interface
-          >>> class I1(Interface): pass
-          ...
-          >>> class I2(I1): pass
-          ...
-          >>> spec = InterfaceSpecification(I2)
-          >>> int(spec.__signature__ == "%s\\t%s\\t%s" % (
-          ...    I2.__identifier__, I1.__identifier__,
-          ...    Interface.__identifier__))
-          1
+    def __nonzero__(self):
+        """Test whether there are any interfaces in a specification.
 
+        >>> from zope.interface import Interface
+        >>> class I1(Interface): pass
+        ...
+        >>> spec = InterfaceSpecification(I1)
+        >>> int(bool(spec))
+        1
+        >>> spec = InterfaceSpecification()
+        >>> int(bool(spec))
+        0
         """
-        self.__signature__ = '\t'.join([iface.__identifier__ for iface in iro])
-
+        return bool(self.interfaces)
 
     def __contains__(self, interface):
         """Test whether an interface is in the specification
@@ -425,7 +637,7 @@
         """
         if other is None:
             other = _empty
-        return self.__class__(self, other)
+        return self.__class__(*_flattenSpecs((self, other), []))
 
     __radd__ = __add__
 
@@ -465,9 +677,9 @@
 
         """
         if other is None:
-            other = _empty
+            other = ()
         else:
-            other = InterfaceSpecification(other)
+            other = _flattenSpecs((other,), [])
 
         ifaces = []
 
@@ -476,17 +688,71 @@
             for oface in other:
                 if oface in iface.__iro__:
                     break
-                else:
-                    ifaces.append(iface)
+            else:
+                ifaces.append(iface)
 
         return self.__class__(*ifaces)
 
 
-class ImplementsSpecification(InterfaceSpecification):
+class PicklableSpec(Spec):
+    """Mix-in that adds picklability
+
+    This is done using a mix-in to prevent regular interface specs
+    from being pickled.
+    
+    """
+
+    __safe_for_unpickling__ = True
+
+    def __reduce__(self):
+        return self.__class__, self.interfaces
+
+
+
+def _flattenSpecs(specs, result):
+    """Flatten a sequence of interfaces and interface specs to interfaces
+
+    >>> I1 = InterfaceClass('I1', (), {})
+    >>> I2 = InterfaceClass('I2', (), {})
+    >>> I3 = InterfaceClass('I3', (), {})
+    >>> spec = InterfaceSpecification(I1, I2)
+    >>> r = _flattenSpecs((I3, spec), [])
+    >>> int(r == [I3, I1, I2])
+    1
+
+    """
+    try:
+        # catch bad spec by seeing if we can iterate over it
+        ispecs = iter(specs)
+    except TypeError:
+        # Must be a bad spec
+        raise exceptions.BadImplements(specs)
+
+    for spec in ispecs:
+        # We do this rather than isinstance because it works w proxies classes
+        if InterfaceClass in spec.__class__.__mro__:
+            if spec not in result:
+                result.append(spec)
+        elif spec is specs:
+            # Try to avoid an infinate loop by getting a string!
+            raise TypeError("Bad interface specification", spec)
+        else:
+            _flattenSpecs(spec, result)
+
+    return result
+
+_empty = InterfaceSpecification()
+
+def ImplementsSpecification(*interfaces):
+    return Implements(*_flattenSpecs(interfaces, []))
+    
+class Implements(PicklableSpec):
+
+    __module__ = 'zope.interface'
 
     _cspec = None
     def setClass(self, cls):
-        self._cspec = ImplementsSpecification(_gatherSpecs(cls, []))
+        self._cspec = Spec(*_flattenSpecs(_gatherSpecs(cls, []), []))
         self.__signature__ = self._cspec.__signature__
 
     def __get__(self, inst, cls):
@@ -521,16 +787,27 @@
 
         return InterfaceSpecification(_gatherSpecs(cls, []))
 
-class OnlyImplementsSpecification(ImplementsSpecification):
+
+def ImplementsOnlySpecification(*interfaces):
+    return Only(*_flattenSpecs(interfaces, []))
+
+class Only(Implements):
+
+    __module__ = 'zope.interface'
 
     only = True
 
     def __init__(self, *interfaces):
-        ImplementsSpecification.__init__(self, *interfaces)
+        Spec.__init__(self, *interfaces)
         self.__signature__ = "only(%s)" % self.__signature__
 
 
-class ProvidesSpecification(InterfaceSpecification):
+def ProvidesSpecification(*interfaces):
+    return Provides(*_flattenSpecs(interfaces, []))
+
+class Provides(PicklableSpec):
+
+    __module__ = 'zope.interface'
 
     def __get__(self, inst, cls):
         """Make sure that a class __provides__ doesn't leak to an instance
@@ -560,170 +837,8 @@
         raise AttributeError, '__provides__'
 
 
-class ObjectSpecificationDescriptor:
-
-    def __get__(self, inst, cls):
-        """Get an object specification for an object
-
-        For example::
-
-          >>> from zope.interface import Interface
-          >>> class IFoo(Interface): pass
-          ...
-          >>> class IFooFactory(Interface): pass
-          ...
-          >>> class C:
-          ...   implements(IFoo)
-          ...   classProvides(IFooFactory)
-          >>> [i.__name__ for i in C.__providedBy__]
-          ['IFooFactory']
-          >>> [i.__name__ for i in C().__providedBy__]
-          ['IFoo']
-
-        """
-
-        # Get an ObjectSpecification bound to either an instance or a class,
-        # depending on how we were accessed.
-        if inst is None:
-            return ObjectSpecification(cls)
-        else:
-            return ObjectSpecification(inst)
-
 _objectSpecificationDescriptor = ObjectSpecificationDescriptor()
 
-class ObjectSpecification(ObjectSpecificationBase):
-    """Provide object specifications
-
-    These combine information for the object and for it's classes.
-
-    For example::
-
-        >>> from zope.interface import Interface
-        >>> class I1(Interface): pass
-        ...
-        >>> class I2(Interface): pass
-        ...
-        >>> class I3(Interface): pass
-        ...
-        >>> class I31(I3): pass
-        ...
-        >>> class I4(Interface): pass
-        ...
-        >>> class I5(Interface): pass
-        ...
-        >>> class A: implements(I1)
-        ...
-        >>> class B: __implements__ = I2
-        ...
-        >>> class C(A, B): implements(I31)
-        ...
-        >>> c = C()
-        >>> directlyProvides(c, I4)
-        >>> [i.__name__ for i in providedBy(c)]
-        ['I4', 'I31', 'I1', 'I2']
-        >>> [i.__name__ for i in providedBy(c).flattened()]
-        ['I4', 'I31', 'I3', 'I1', 'I2', 'Interface']
-        >>> int(I1 in providedBy(c))
-        1
-        >>> int(I3 in providedBy(c))
-        0
-        >>> int(providedBy(c).extends(I3))
-        1
-        >>> int(providedBy(c).extends(I31))
-        1
-        >>> int(providedBy(c).extends(I5))
-        0
-        >>> class COnly(A, B): implementsOnly(I31)
-        ...
-        >>> class D(COnly): implements(I5)
-        ...
-        >>> c = D()
-        >>> directlyProvides(c, I4)
-        >>> [i.__name__ for i in providedBy(c)]
-        ['I4', 'I5', 'I31']
-        >>> [i.__name__ for i in providedBy(c).flattened()]
-        ['I4', 'I5', 'I31', 'I3', 'Interface']
-        >>> int(I1 in providedBy(c))
-        0
-        >>> int(I3 in providedBy(c))
-        0
-        >>> int(providedBy(c).extends(I3))
-        1
-        >>> int(providedBy(c).extends(I1))
-        0
-        >>> int(providedBy(c).extends(I31))
-        1
-        >>> int(providedBy(c).extends(I5))
-        1
-    """
-
-    __slots__ = ['_specslot']
-    only = True
-
-    def _v_spec(self):
-        spec = getattr(self, '_specslot', self)
-        if spec is not self:
-            return spec
-
-        ob = self.ob
-        provides = getattr(ob, '__provides__', None)
-        if provides is not None:
-            result = [provides]
-        else:
-            result = []
-
-        try:
-            cls = ob.__class__
-        except AttributeError:
-            pass
-        else:
-            _gatherSpecs(cls, result)
-
-        self._specslot = spec = InterfaceSpecification(*result)
-
-        return spec
-
-    _v_spec = property(_v_spec)
-
-    def __contains__(self, interface):
-        return interface in self._v_spec
-
-    def __iter__(self):
-        return iter(self._v_spec)
-
-    def flattened(self):
-        return self._v_spec.flattened()
-
-    def extends(self, interface):
-        return self._v_spec.extends(interface)
-
-    def __add__(self, other):
-        return self._v_spec + other
-    __radd__ = __add__
-
-    def __sub__(self, other):
-        return self._v_spec - other
-
-def providedBy(ob):
-
-    # Here we have either a special object, an old-style declaration
-    # or a descriptor
-
-    try:
-        r = ob.__providedBy__
-
-        # We might have gotten a descriptor from an instance of a
-        # class (like an ExtensionClass) that doesn't support
-        # descriptors.  We'll make sure we got one by trying to get
-        # the only attribute, which all specs have.
-        r.only
-
-    except AttributeError:
-        # No descriptor, so fall back to a plain object spec
-        r = ObjectSpecification(ob)
-
-    return r
-
 def classImplementsOnly(cls, *interfaces):
     """Declare the only interfaces implemented by instances of a class
 
@@ -758,9 +873,9 @@
     whatever interfaces instances of ``A`` and ``B`` implement.
 
     """
-    spec = OnlyImplementsSpecification(*interfaces)
+    spec = ImplementsOnlySpecification(*interfaces)
     spec.only = True
-    _setImplements(cls, OnlyImplementsSpecification(*interfaces))
+    _setImplements(cls, ImplementsOnlySpecification(*interfaces))
 
 def directlyProvides(object, *interfaces):
     """Declare interfaces declared directly for an object
@@ -889,24 +1004,9 @@
     """
     return getattr(object, "__provides__", _empty)
 
-
-class metaclasshooker:
-
-    def __init__(self, metaclass):
-        self.metaclass = metaclass
-
-    def __call__(self, name, bases, dict):
-        metaclass = self.metaclass
-        if metaclass is None:
-            if bases:
-                metaclass = type(bases[0])
-            else:
-                metaclass = ClassType
-
-        cls = metaclass(name, bases, dict)
-        _setImplements(cls, dict['__implements__'])
-
-        return cls
+def _implements_advice(cls):
+    _setImplements(cls, cls.__dict__['__implements__'])
+    return cls
 
 def _implements(name, spec):
     frame = sys._getframe(2)
@@ -920,11 +1020,7 @@
         raise TypeError(name+" can be used only once in a class definition.")
 
     locals["__implements__"] = spec
-
-    metaclass = locals.get('__metaclass__')
-    if metaclass is None:
-        metaclass = frame.f_globals.get('__metaclass__')
-    locals["__metaclass__"] = metaclasshooker(metaclass)
+    addClassAdvisor(_implements_advice, depth=3)
 
 def implements(*interfaces):
     """Declare interfaces implemented by instances of a class
@@ -1045,7 +1141,7 @@
     instances of ``A`` and ``B`` implement.
 
     """
-    spec = ImplementsSpecification(interfaces)
+    spec = ImplementsOnlySpecification(interfaces)
     spec.only = True
     _implements("implements", spec)
 
@@ -1191,7 +1287,7 @@
 
             implements = getattr(cls, '__implements__', None)
             if implements is not None:
-                implements = OnlyImplementsSpecification(implements)
+                implements = ImplementsOnlySpecification(implements)
 
             return implements
 
@@ -1202,48 +1298,65 @@
 
     return d.get(k)
 
+def _finddescr(cls):
+    # Try to find the __providedBy__ descriptor. If we can't find it,
+    # just return the class. 
+
+    d = cls.__dict__.get("__providedBy__", cls)
+    if d is not cls:
+        return d
+    for b in cls.__bases__:
+        d = _finddescr(b)
+        if d is not b:
+            return d
+
+    return cls
+
 def _setImplements(cls, v):
     flags = getattr(cls, '__flags__', heap)
 
     if flags & heap:
         cls.__implements__ = v
-        cls.__providedBy__ = _objectSpecificationDescriptor
-    else:
-        _implements_reg[cls] = v
 
-    v.setClass(cls)
+        # Add a __providedBy__ descriptor if there isn't already one.
+        # If there is one and it's not in the dict, then make a copy
+        # here.
 
-def _flattenSpecs(specs, result):
-    """Flatten a sequence of interfaces and interface specs to interfaces
-
-    >>> I1 = InterfaceClass('I1', (), {})
-    >>> I2 = InterfaceClass('I2', (), {})
-    >>> I3 = InterfaceClass('I3', (), {})
-    >>> spec = InterfaceSpecification(I1, I2)
-    >>> r = _flattenSpecs((I3, spec), [])
-    >>> int(r == [I3, I1, I2])
-    1
+        try:
+            cls.__providedBy__
+        except AttributeError:
+            # No existing descriptor, add one
+            cls.__providedBy__ = _objectSpecificationDescriptor
+        else:
+            # Hm, the class already has a descriptor, let's get it and
+            # see if it's the right kind.
+            try:
+                mro = cls.__mro__
+            except AttributeError:
+                pb = _finddescr(cls)
+                if pb is cls:
+                    pb = None
+            else:
+                for c in mro:
+                    pb = c.__dict__.get("__providedBy__", c)
+                    if pb is not c:
+                        break
+                else: # no break
+                    pb = None
+
+            if not isinstance(pb, ObjectSpecificationDescriptor):
+                raise TypeError(
+                    cls,
+                    "has a __providedBy__ descriptor of the wrong type",
+                    pb)
 
-    """
-    try:
-        # catch bad spec by seeing if we can iterate over it
-        ispecs = iter(specs)
-    except TypeError:
-        # Must be a bad spec
-        raise exceptions.BadImplements(specs)
+            if "__providedBy__" not in cls.__dict__:
+                cls.__providedBy__ = pb
 
-    for spec in ispecs:
-        # We do this rather than isinstance because it works w proxies classes
-        if InterfaceClass in spec.__class__.__mro__:
-            if spec not in result:
-                result.append(spec)
-        elif spec is specs:
-            # Try to avoid an infinate loop by getting a string!
-            raise TypeError("Bad interface specification", spec)
-        else:
-            _flattenSpecs(spec, result)
+    else:
+        _implements_reg[cls] = v
 
-    return result
+    v.setClass(cls)
 
 def _getmro(C, r):
   if C not in r: r.append(C)
@@ -1258,7 +1371,7 @@
             stop = implements.only
         except AttributeError:
             # Must be an old-style interface spec
-            implements = OnlyImplementsSpecification(
+            implements = ImplementsOnlySpecification(
                 _flattenSpecs([implements], []))
             stop = 1
             _setImplements(cls, implements)
@@ -1280,7 +1393,7 @@
             stop = implements.only
         except AttributeError:
             # Must be an old-style interface spec
-            implements = OnlyImplementsSpecification(
+            implements = ImplementsOnlySpecification(
                 _flattenSpecs([implements], []))
             stop = 1
             _setImplements(cls, implements)
@@ -1296,7 +1409,8 @@
             result.append(cspec)
             return result
 
-        # No cached cspec. Compute one if we're being called recursively:
+        # No cached cspec. Compute one if we're being called recursively.
+        # We know we're being called recursively is result is not empty!
         if result:
             implements.setClass(cls)
             cspec = implements._cspec
@@ -1310,9 +1424,6 @@
         _gatherSpecs(b, result)
 
     return result
-
-_empty = InterfaceSpecification()
-
 
 # DocTest:
 if __name__ == "__main__":


=== Zope3/src/zope/interface/interface.py 1.9 => 1.9.4.1 ===
--- Zope3/src/zope/interface/interface.py:1.9	Sat May  3 12:36:05 2003
+++ Zope3/src/zope/interface/interface.py	Sun Jun 22 10:23:44 2003
@@ -18,7 +18,6 @@
 """
 
 import sys
-from inspect import currentframe
 from types import FunctionType
 
 CO_VARARGS = 4


=== Zope3/src/zope/interface/interfaces.py 1.13 => 1.13.4.1 ===
--- Zope3/src/zope/interface/interfaces.py:1.13	Sat May  3 12:36:36 2003
+++ Zope3/src/zope/interface/interfaces.py	Sun Jun 22 10:23:44 2003
@@ -508,6 +508,10 @@
         not raise an error. Doing so has no effect.
         """
 
+    def __nonzero__():
+        """Return a true value of the interface specification is non-empty
+        """
+
     __signature__ = Attribute("""A specification signature
 
     The signature should change if any of the interfaces in the


=== Zope3/src/zope/interface/pyskel.py 1.2 => 1.2.28.1 ===
--- Zope3/src/zope/interface/pyskel.py:1.2	Wed Dec 25 09:13:42 2002
+++ Zope3/src/zope/interface/pyskel.py	Sun Jun 22 10:23:44 2003
@@ -55,11 +55,6 @@
                                   isinstance(ades[1], Attribute),
                                   namesAndDescriptions)
 
-    # if namesAndDescriptions and print_iface:
-    #     print
-    #     print "    ######################################"
-    #     print "    # from:", name
-
     for aname, ades in namesAndDescriptions:
         if isinstance(ades, Method):
             sig = ades.getSignatureString()[1:-1]
@@ -68,10 +63,6 @@
             print
             print "    def %s(%s):" % (aname, sig)
             print '        "See %s"' % name
-            # print
-            # print
-            # print "    %s.__doc__ = '%%s\\n\\n%%s' %% (%s['%s'].__doc__, %s.__doc__" % (
-            #     aname, top.__name__, aname, aname)
 
         elif isinstance(ades, Attribute):
             print
@@ -91,22 +82,16 @@
     class_name = iface.__name__
     if class_name.startswith('I'):
         class_name = class_name[1:]
+    print "from zope.interface import implements"
     print "from %s import %s" % (iface.__module__, iface.__name__)
     print
     print "class %s:" %class_name
     print "    __doc__ = %s.__doc__" % iface.__name__
     print
-    print "    __implements__ = ", iface.__name__
+    print "    implements(%s)" %iface.__name__
     print
-    # print "    ############################################################"
-    # print "    # Implementation methods for interface"
-    # print "    #", name
 
     rskel(iface, iface, 0)
-
-    # print
-    # print "    #"
-    # print "    ############################################################"
 
 
 def resolve(name, _silly=('__doc__',), _globals={}):


=== Zope3/src/zope/interface/type.py 1.8 => 1.8.4.1 ===
--- Zope3/src/zope/interface/type.py:1.8	Sat May  3 12:36:05 2003
+++ Zope3/src/zope/interface/type.py	Sun Jun 22 10:23:44 2003
@@ -19,13 +19,13 @@
 """
 __metaclass__ = type # All classes are new style when run with Python 2.2+
 
-from zope.interface import Interface, providedBy
+from zope.interface import providedBy, implements
 from zope.interface.interfaces import IInterface
 from zope.interface.interfaces import ITypeRegistry
 
 class TypeRegistry:
 
-    __implements__ = ITypeRegistry
+    implements(ITypeRegistry)
 
     # XXX This comment doesn't seem to be correct, because the mapping is
     # from interface -> object.  There are no tuples that I see.  Also,

=== Removed File Zope3/src/zope/interface/_callableimplements.py ===

=== Removed File Zope3/src/zope/interface/implements.py ===




More information about the Zodb-checkins mailing list