[Zope3-checkins] CVS: Zope3/src/zope/interface - __init__.py:1.1.2.1 _flatten.py:1.1.2.1 adapter.py:1.1.2.1 document.py:1.1.2.1 exceptions.py:1.1.2.1 implementor.py:1.1.2.1 implements.py:1.1.2.1 interface.py:1.1.2.1 interfaces.py:1.1.2.1 pyskel.py:1.1.2.1 type.py:1.1.2.1 verify.py:1.1.2.1
Jim Fulton
jim@zope.com
Mon, 23 Dec 2002 14:32:57 -0500
Update of /cvs-repository/Zope3/src/zope/interface
In directory cvs.zope.org:/tmp/cvs-serv19908/zope/interface
Added Files:
Tag: NameGeddon-branch
__init__.py _flatten.py adapter.py document.py exceptions.py
implementor.py implements.py interface.py interfaces.py
pyskel.py type.py verify.py
Log Message:
Initial renaming before debugging
=== Added File Zope3/src/zope/interface/__init__.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
#
##############################################################################
"""Interfaces
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:
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.
The package has several public modules:
o Attribute has the implementation for interface attributes
for people who want to build interfaces by hand.
(Maybe someone should cry YAGNI for this. ;)
o Document has a utility for documenting an interface as structured text.
o Exceptions has the interface-defined exceptions
o IAttribute defines the attribute descriptor interface.
o IElement defined the base interface for IAttribute, IInterface,
and IMethod.
o IInterface defines the interface interface
o IMethod defined the method interface.
o Implements has various utilities for examining interface assertions.
o Method has the implementation for interface methods. See above.
o Verify has utilities for verifying (sort of) interfaces.
See the module doc strings for more information.
There is also a script, pyself.py in the package that can be used to
create interface skeletins. Run it without arguments to get documentation.
Revision information:
$Id: __init__.py,v 1.1.2.1 2002/12/23 19:32:54 jim Exp $
"""
from zope.interface.interface import Interface, _wire
# Need to actually get the interface elements to implement the right interfaces
_wire()
del _wire
=== Added File Zope3/src/zope/interface/_flatten.py ===
##############################################################################
#
# Copyright (c) 2002 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.
#
##############################################################################
"""Adapter-style interface registry
See Adapter class.
$Id: _flatten.py,v 1.1.2.1 2002/12/23 19:32:54 jim Exp $
"""
__metaclass__ = type # All classes are new style when run with Python 2.2+
from zope.interface import Interface
def _flatten(implements, include_None=0):
"""Flatten an implements spec to a list of interfaces
The list includes all base interfaces of the interface(s) in
implements. Each interface is listed only once and more
specific interfaces are listed before less specific
interfaces. This is similar to Python 2.2's MRO.
"""
interfaces = []
_flatten_recurse(implements, interfaces)
interfaces.reverse()
seen = {}
flattened = []
for interface in interfaces:
if interface not in seen:
seen[interface] = 1
flattened.append(interface)
flattened.reverse()
if include_None:
flattened.append(None)
return flattened
def _flatten_recurse(implements, list):
if implements.__class__ == tuple:
for i in implements:
_flatten_recurse(i, list)
else:
_flatten_recurse_interface(implements, list)
def _flatten_recurse_interface(interface, list):
list.append(interface)
if interface is None:
return
for i in interface.__bases__:
_flatten_recurse_interface(i, list)
=== Added File Zope3/src/zope/interface/adapter.py ===
##############################################################################
#
# Copyright (c) 2002 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.
#
##############################################################################
"""Adapter-style interface registry
See Adapter class.
$Id: adapter.py,v 1.1.2.1 2002/12/23 19:32:54 jim Exp $
"""
__metaclass__ = type # All classes are new style when run with Python 2.2+
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.interface._flatten import _flatten
from zope.interface.interfaces import IAdapterRegistry
class AdapterRegistry:
"""Adapter-style interface registry
"""
__implements__ = IAdapterRegistry
# The implementation uses a mapping:
#
# { (required_interface, provided_interface) ->
# (registered_provides, component) }
#
# Where the registered provides is what was registered and
# provided may be some base interface
def __init__(self, data=None):
if data is None:
data = {}
self._reg = data
def _registerAllProvided(self, require, primary_provide, object, provide):
# Registers a component using (require, provide) as a key.
# Also registers superinterfaces of the provided interface,
# stopping when the registry already has a component
# that provides a more general interface or when the Base is Interface.
reg = self._reg
reg[(require, provide)] = (primary_provide, object)
bases = getattr(provide, '__bases__', ())
for base in bases:
if base is Interface:
# Never register the say-nothing Interface.
continue
existing = reg.get((require, base), None)
if existing is not None:
existing_provide = existing[0]
if existing_provide is not primary_provide:
if not existing_provide.extends(primary_provide):
continue
# else we are registering a general component
# after a more specific component.
self._registerAllProvided(require, primary_provide, object, base)
def register(self, require, provide, object):
if require is not None and not IInterface.isImplementedBy(require):
raise TypeError(
"The require argument must be an interface (or None)")
if not IInterface.isImplementedBy(provide):
raise TypeError(
"The provide argument must be an interface (or None)")
self._registerAllProvided(require, provide, object, provide)
def get(self, (ob_interface, provide), default=None, filter=None):
"""
Finds a registered component that provides the given interface.
Returns None if not found.
"""
for interface in _flatten(ob_interface, 1):
c = self._reg.get((interface, provide))
if c:
c = c[1]
if filter is None:
return c
if filter(c):
return c
return default
def getForObject(self, object, interface, filter=None):
return self.get((getattr(object, '__implements__', None), interface),
filter=filter)
def getRegistered(self, require, provide):
data = self._reg.get((require, provide))
if data:
registered_provide, object = data
if registered_provide == provide:
return object
return None
def getRegisteredMatching(self,
required_interfaces=None,
provided_interfaces=None):
if IInterface.isImplementedBy(required_interfaces):
required_interfaces = (required_interfaces, )
if provided_interfaces:
if IInterface.isImplementedBy(provided_interfaces):
provided_interfaces = (provided_interfaces, )
r = {}
if required_interfaces:
# Both specified
for required in _flatten(required_interfaces, 1):
for provided in provided_interfaces:
v = self._reg.get((required, provided))
if v:
rprovided, o = v
r[required, rprovided] = o
else:
# Only provided specified
for (required, provided), (rprovided, o) in self._reg.items():
for p in provided_interfaces:
if provided.extends(p, 0):
r[required, rprovided] = o
break
return [(required, provided, o)
for ((required, provided), o) in r.items()]
elif required_interfaces:
# Just required specified
required_interfaces = _flatten(required_interfaces, 1)
return [(required, provided, o)
for (required, provided), (rprovided, o)
in self._reg.items()
if ((required in required_interfaces)
and
provided == rprovided
)
]
else:
# Nothing specified
return [(required, provided, o)
for (required, provided), (rprovided, o)
in self._reg.items()
if provided == rprovided
]
=== Added File Zope3/src/zope/interface/document.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
#
##############################################################################
""" Pretty-Print an Interface object as structured text (Yum)
This module provides a function, asStructuredText, for rendering an
interface as structured text.
Revision information:
$Id: document.py,v 1.1.2.1 2002/12/23 19:32:54 jim Exp $
"""
from string import maketrans
def asStructuredText(I, munge=0):
""" Output structured text format. Note, this will wack any existing
'structured' format of the text. """
r = ["%s\n\n" % I.getName()]
outp = r.append
level = 1
if I.getDoc():
outp(_justify_and_indent(_trim_doc_string(I.getDoc()), level)+ "\n\n")
if I.getBases():
outp((" " * level) + "This interface extends:\n\n")
level = level + 1
for b in I.getBases():
item = "o %s" % b.getName()
outp(_justify_and_indent(_trim_doc_string(item), level, munge)
+ "\n\n")
level = level - 1
outp(_justify_and_indent("Attributes:", level, munge)+'\n\n')
level = level + 1
namesAndDescriptions = I.namesAndDescriptions()
namesAndDescriptions.sort()
for name, desc in namesAndDescriptions:
if not hasattr(desc, 'getSignatureString'): # ugh...
item = "%s -- %s" % (desc.getName(),
desc.getDoc() or 'no documentation')
outp(_justify_and_indent(_trim_doc_string(item), level, munge)
+ "\n\n")
level = level - 1
outp(_justify_and_indent("Methods:", level, munge)+'\n\n')
level = level + 1
for name, desc in namesAndDescriptions:
if hasattr(desc, 'getSignatureString'): # ugh...
item = "%s%s -- %s" % (desc.getName(),
desc.getSignatureString(),
desc.getDoc() or 'no documentation')
outp(_justify_and_indent(_trim_doc_string(item), level, munge)
+ "\n\n")
return "".join(r)
def _trim_doc_string(text):
"""
Trims a doc string to make it format
correctly with structured text.
"""
text = text.strip().replace('\r\n', '\n')
lines = text.split('\n')
nlines = [lines[0]]
if len(lines) > 1:
min_indent=None
for line in lines[1:]:
indent=len(line) - len(line.lstrip())
if indent < min_indent or min_indent is None:
min_indent=indent
for line in lines[1:]:
nlines.append(line[min_indent:])
return '\n'.join(nlines)
_trans = maketrans("\r\n", " ")
def _justify_and_indent(text, level, munge=0, width=72):
""" indent and justify text, rejustify (munge) if specified """
lines = []
if munge:
line = " " * level
text = text.translate(text, _trans).strip().split()
for word in text:
line = ' '.join([line, word])
if len(line) > width:
lines.append(line)
line = " " * level
else:
lines.append(line)
return "\n".join(lines)
else:
text = text.replace("\r\n", "\n").split("\n")
for line in text:
lines.append( (" " * level) + line)
return '\n'.join(lines)
=== Added File Zope3/src/zope/interface/exceptions.py ===
##############################################################################
#
# Copyright (c) 2002 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.
#
##############################################################################
"""
$Id: exceptions.py,v 1.1.2.1 2002/12/23 19:32:54 jim Exp $
"""
class DoesNotImplement(Exception):
""" This object does not implement """
def __init__(self, interface):
self.interface = interface
def __str__(self):
return """An object does not implement interface %(interface)s
""" % self.__dict__
class BrokenImplementation(Exception):
"""An attribute is not completely implemented.
"""
def __init__(self, interface, name):
self.interface=interface
self.name=name
def __str__(self):
return """An object has failed to implement interface %(interface)s
The %(name)s attribute was not provided.
""" % self.__dict__
class BrokenMethodImplementation(Exception):
"""An method is not completely implemented.
"""
def __init__(self, method, mess):
self.method=method
self.mess=mess
def __str__(self):
return """The implementation of %(method)s violates its contract
because %(mess)s.
""" % self.__dict__
class InvalidInterface(Exception):
"""The interface has invalid contents
"""
class BadImplements(TypeError):
"""An implementation assertion is invalid
because it doesn't contain an interface or a sequence of valid
implementation assertions.
"""
=== Added File Zope3/src/zope/interface/implementor.py ===
##############################################################################
#
# Copyright (c) 2002 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.
#
##############################################################################
"""Adapter-style interface registry
See Adapter class.
$Id: implementor.py,v 1.1.2.1 2002/12/23 19:32:54 jim Exp $
"""
__metaclass__ = type # All classes are new style when run with Python 2.2+
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.interface.interfaces import IImplementorRegistry
class ImplementorRegistry:
"""Implementor-style interface registry
"""
__implements__ = IImplementorRegistry
# The implementation uses a mapping:
#
# { provided_interface -> (registered_provides, component) }
#
# Where the registered provides is what was registered and
# provided may be some base interface
def __init__(self):
self._reg = {}
def _registerAllProvided(self, primary_provide, object, provide):
# Registers a component using (require, provide) as a key.
# Also registers superinterfaces of the provided interface,
# stopping when the registry already has a component
# that provides a more general interface or when the Base is Interface.
reg = self._reg
reg[provide] = (primary_provide, object)
bases = getattr(provide, '__bases__', ())
for base in bases:
if base is Interface:
# Never register the say-nothing Interface.
continue
existing = reg.get(base, None)
if existing is not None:
existing_provide = existing[0]
if existing_provide is not primary_provide:
if not existing_provide.extends(primary_provide):
continue
# else we are registering a general component
# after a more specific component.
self._registerAllProvided(primary_provide, object, base)
def register(self, provide, object):
if not IInterface.isImplementedBy(provide):
raise TypeError(
"The provide argument must be an interface (or None)")
self._registerAllProvided(provide, object, provide)
def get(self, provide, default=None):
"""
Finds a registered component that provides the given interface.
Returns None if not found.
"""
c = self._reg.get(provide)
if c is not None:
return c[1]
return default
=== Added File Zope3/src/zope/interface/implements.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
#
##############################################################################
"""Implemantation assertion facilities.
Revision information:
$Id: implements.py,v 1.1.2.1 2002/12/23 19:32:54 jim Exp $
"""
from zope.interface import exceptions
from zope.interface.verify import verifyClass
from zope.interface.interface import InterfaceClass
from types import TupleType, ClassType, StringType
# Special value indicating the object supports
# what its class supports.
CLASS_INTERFACES = 1
ClassTypes = ClassType, type
_typeImplements = {}
def getImplements(object):
# Decide whether or not the object is a class. If it is a class,
# return it's __class_implements__ rather than its __implements__.
if isinstance(object, ClassTypes):
ci = getattr(object, '__class_implements__', None)
if ci is not None:
return ci
else:
impl = getattr(object, '__implements__', None)
if impl is not None:
return impl
return _typeImplements.get(type(object))
def getImplementsOfInstances(klass):
if isinstance(klass, ClassTypes):
return getattr(klass, '__implements__', None)
else:
return _typeImplements.get(klass)
def visitImplements(implements, object, visitor, getInterface=None):
"""Call visitor for each interace.
Visits the interfaces described by an __implements__ attribute,
invoking the visitor for each interface object.
If the visitor returns anything true, the loop stops.
This does not, and should not, visit superinterfaces.
"""
# this allows us to work with proxy wrappers in Python 2.2,
# yet remain compatible with earlier versions of python.
implements_class = getattr(implements, '__class__', None)
if implements_class == InterfaceClass or \
isinstance(implements, InterfaceClass):
return visitor(implements)
elif implements == CLASS_INTERFACES:
klass = getattr(object, '__class__', None)
if klass is not None:
i = getImplementsOfInstances(klass)
if i:
return visitImplements(i, object, visitor, getInterface)
elif implements_class == StringType or type(implements) is StringType:
if getInterface is not None:
# Look up a named interface.
i = getInterface(object, implements)
if i is not None:
return visitImplements(i, object, visitor, getInterface)
elif implements_class == TupleType or type(implements) is TupleType:
for i in implements:
r = visitImplements(i, object, visitor, getInterface)
if r:
# If the visitor returns anything true, stop.
return r
else:
if implements_class is not None and \
type(implements) != implements_class:
raise exceptions.BadImplements(
"""__implements__ should be an interface or tuple,
not a %s pretending to be a %s"""
% (type(implements).__name__, implements_class.__name__)
)
raise exceptions.BadImplements(
"""__implements__ should be an interface or tuple,
not a %s""" % type(implements).__name__)
return None
def assertTypeImplements(type, interfaces):
"""Assign a set of interfaces to a Python type such as int, str, tuple,
list and dict.
"""
_typeImplements[type] = interfaces
def objectImplements(object, getInterface=None):
r = []
implements = getImplements(object)
if not implements:
return r
visitImplements(implements, object, r.append, getInterface)
return r
def instancesOfObjectImplements(klass, getInterface=None):
r = []
implements = getImplementsOfInstances(klass)
if not implements:
return r
visitImplements(implements, klass, r.append, getInterface)
return r
def _flatten(i, append):
append(i)
bases = i.getBases()
if bases:
for b in bases:
_flatten(b, append)
def flattenInterfaces(interfaces, remove_duplicates=1):
res = []
for i in interfaces:
_flatten(i, res.append)
if remove_duplicates:
# Remove duplicates in reverse.
# Similar to Python 2.2's method resolution order.
seen = {}
index = len(res) - 1
while index >= 0:
i = res[index]
if i in seen:
del res[index]
else:
seen[i] = 1
index = index - 1
return res
def implements(klass, interface, check=1):
if check:
verifyClass(interface, klass, tentative=1)
old = getattr(klass, '__implements__', None)
if old is None:
klass.__implements__ = interface
else:
klass.__implements__ = old, interface
=== Added File Zope3/src/zope/interface/interface.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
#
##############################################################################
"""Interface object implementation
Revision information:
$Id: interface.py,v 1.1.2.1 2002/12/23 19:32:54 jim Exp $
"""
"""Interface object implementation
Revision information:
$Id: interface.py,v 1.1.2.1 2002/12/23 19:32:54 jim Exp $
"""
from inspect import currentframe
from types import FunctionType
sig_traits = ['positional', 'required', 'optional', 'varargs', 'kwargs']
CO_VARARGS = 4
CO_VARKEYWORDS = 8
class Element(object):
# We can't say this yet because we don't have enough
# infrastructure in place.
#
#__implements__ = IElement
__tagged_values = {}
def __init__(self, __name__, __doc__=''):
"""Create an 'attribute' description
"""
if not __doc__ and __name__.find(' ') >= 0:
__doc__ = __name__
__name__ = None
self.__name__=__name__
self.__doc__=__doc__
def getName(self):
""" Returns the name of the object. """
return self.__name__
def getDoc(self):
""" Returns the documentation for the object. """
return self.__doc__
def getTaggedValue(self, tag):
""" Returns the value associated with 'tag'. """
return self.__tagged_values[tag]
def getTaggedValueTags(self):
""" Returns a list of all tags. """
return self.__tagged_values.keys()
def setTaggedValue(self, tag, value):
""" Associates 'value' with 'key'. """
self.__tagged_values[tag] = value
class InterfaceClass(Element):
"""Prototype (scarecrow) Interfaces Implementation."""
# We can't say this yet because we don't have enough
# infrastructure in place.
#
#__implements__ = IInterface
def __init__(self, name, bases=(), attrs=None, __doc__=None,
__module__=None):
if __module__ is None:
if attrs is not None and ('__module__' in attrs):
__module__ = attrs['__module__']
del attrs['__module__']
else:
try:
# Figure out what module defined the interface.
# This is how cPython figures out the module of
# a class, but of course it does it in C. :-/
__module__ = currentframe().f_back.f_globals['__name__']
except (AttributeError, KeyError):
pass
self.__module__ = __module__
for b in bases:
if not isinstance(b, InterfaceClass):
raise TypeError, 'Expected base interfaces'
# Python expects __bases__ to be a tuple.
self.__bases__ = tuple(bases)
if attrs is None:
attrs = {}
if '__doc__' in attrs:
if __doc__ is None:
__doc__ = attrs['__doc__']
del attrs['__doc__']
if __doc__ is not None:
self.__doc__ = __doc__
else:
self.__doc__ = ""
Element.__init__(self, name, __doc__)
for k, v in attrs.items():
if isinstance(v, Attribute):
v.interface = name
if not v.__name__:
v.__name__ = k
elif isinstance(v, FunctionType):
attrs[k] = fromFunction(v, name, name=k)
else:
raise InvalidInterface("Concrete attribute, %s" % k)
self.__attrs = attrs
def getBases(self):
return self.__bases__
def extends(self, other, strict=1):
"""Does an interface extend another?"""
if not strict and self is other:
return True
for b in self.__bases__:
if b == other: return True
if b.extends(other): return True
return False
def isEqualOrExtendedBy(self, other):
"""Same interface or extends?"""
if self == other:
return True
return other.extends(self)
def isImplementedBy(self, object):
"""Does the given object implement the interface?"""
i = getImplements(object)
if i is not None:
return visitImplements(
i, object, self.isEqualOrExtendedBy, self._getInterface)
return False
def isImplementedByInstancesOf(self, klass):
"""Do instances of the given class implement the interface?"""
i = getImplementsOfInstances(klass)
if i is not None:
return visitImplements(
i, klass, self.isEqualOrExtendedBy, self._getInterface)
return False
def names(self, all=0):
"""Return the attribute names defined by the interface."""
if not all:
return self.__attrs.keys()
r = {}
for name in self.__attrs.keys():
r[name] = 1
for base in self.__bases__:
for name in base.names(all):
r[name] = 1
return r.keys()
def __iter__(self):
return iter(self.names(1))
def namesAndDescriptions(self, all=0):
"""Return attribute names and descriptions defined by interface."""
if not all:
return self.__attrs.items()
r = {}
for name, d in self.__attrs.items():
r[name] = d
for base in self.__bases__:
for name, d in base.namesAndDescriptions(all):
if name not in r:
r[name] = d
return r.items()
def getDescriptionFor(self, name):
"""Return the attribute description for the given name."""
r = self.queryDescriptionFor(name)
if r is not None:
return r
raise KeyError, name
__getitem__ = getDescriptionFor
def __contains__(self, name):
return self.queryDescriptionFor(name) is not None
def queryDescriptionFor(self, name, default=None):
"""Return the attribute description for the given name."""
r = self.__attrs.get(name, self)
if r is not self:
return r
for base in self.__bases__:
r = base.queryDescriptionFor(name, self)
if r is not self:
return r
return default
get = queryDescriptionFor
def deferred(self):
"""Return a defered class corresponding to the interface."""
if hasattr(self, "_deferred"): return self._deferred
klass={}
exec "class %s: pass" % self.__name__ in klass
klass=klass[self.__name__]
self.__d(klass.__dict__)
self._deferred=klass
return klass
def _getInterface(self, ob, name):
"""Retrieve a named interface."""
return None
def __d(self, dict):
for k, v in self.__attrs.items():
if isinstance(v, Method) and not (k in dict):
dict[k]=v
for b in self.__bases__: b.__d(dict)
def __repr__(self):
name = self.__name__
m = self.__module__
if m:
name = '%s.%s' % (m, name)
return "<%s %s at %x>" % (self.__class__.__name__, name, id(self))
def __reduce__(self):
return self.__name__
def __cmp(self, o1, o2):
# Yes, I did mean to name this __cmp, rather than __cmp__.
# It is a private method used by __lt__ and __gt__.
# I don't want to override __eq__ because I want the default
# __eq__, which is really fast.
"""Make interfaces sortable
It would ne nice if:
More specific interfaces should sort before less specific ones.
Otherwise, sort on name and module.
But this is too complicated, and we're going to punt on it
for now. XXX
XXX For now, sort on interface and module name.
None is treated as a psuedo interface that implies the loosest
contact possible, no contract. For that reason, all interfaces
sort before None.
"""
if o1 == o2:
return 0
if o1 is None:
return 1
if o2 is None:
return -1
# XXX first and incorrect stab at ordering more specific interfaces first
## if self.extends(other):
## return 1
## if other.extends(self):
## return 0
n1 = (getattr(o1, '__name__', ''),
getattr(getattr(o1, '__module__', None), '__name__', ''))
n2 = (getattr(o2, '__name__', ''),
getattr(getattr(o2, '__module__', None), '__name__', ''))
return cmp(n1, n2)
def __lt__(self, other):
c = self.__cmp(self, other)
#print '<', self, other, c < 0, c
return c < 0
def __gt__(self, other):
c = self.__cmp(self, other)
#print '>', self, other, c > 0, c
return c > 0
Interface = InterfaceClass("Interface")
class Attribute(Element):
"""Attribute descriptions
"""
# We can't say this yet because we don't have enough
# infrastructure in place.
#
#__implements__ = IAttribute
class Method(Attribute):
"""Method interfaces
The idea here is that you have objects that describe methods.
This provides an opportunity for rich meta-data.
"""
# We can't say this yet because we don't have enough
# infrastructure in place.
#
#__implements__ = IMethod
interface=''
def __call__(self, *args, **kw):
raise BrokenImplementation(self.interface, self.__name__)
def getSignatureInfo(self):
info = {}
for t in sig_traits:
info[t] = getattr(self, t)
return info
def getSignatureString(self):
sig = "("
for v in self.positional:
sig = sig + v
if v in self.optional.keys():
sig = sig + "=%s" % `self.optional[v]`
sig = sig + ", "
if self.varargs:
sig = sig + ("*%s, " % self.varargs)
if self.kwargs:
sig = sig + ("**%s, " % self.kwargs)
# slice off the last comma and space
if self.positional or self.varargs or self.kwargs:
sig = sig[:-2]
sig = sig + ")"
return sig
def fromFunction(func, interface='', imlevel=0, name=None):
name = name or func.__name__
m=Method(name, func.__doc__)
defaults=func.func_defaults or ()
c=func.func_code
na=c.co_argcount-imlevel
names=c.co_varnames[imlevel:]
d={}
nr=na-len(defaults)
if nr < 0:
defaults=defaults[-nr:]
nr=0
for i in range(len(defaults)):
d[names[i+nr]]=defaults[i]
m.positional=names[:na]
m.required=names[:nr]
m.optional=d
argno = na
if c.co_flags & CO_VARARGS:
m.varargs = names[argno]
argno = argno + 1
else:
m.varargs = None
if c.co_flags & CO_VARKEYWORDS:
m.kwargs = names[argno]
else:
m.kwargs = None
m.interface=interface
for k, v in func.__dict__.items():
m.setTaggedValue(k, v)
return m
def fromMethod(meth, interface=''):
func = meth.im_func
return fromFunction(func, interface, imlevel=1)
# Now we can create the interesting interfaces and wire them up:
def _wire():
from zope.interface.implements import implements
from zope.interface.interfaces import IAttribute
implements(Attribute, IAttribute)
from zope.interface.interfaces import IMethod
implements(Method, IMethod)
from zope.interface.interfaces import IInterface
implements(InterfaceClass, IInterface)
# We import this here to deal with module dependencies.
from zope.interface.implements import getImplementsOfInstances
from zope.interface.implements import visitImplements, getImplements
from zope.interface.implements import instancesOfObjectImplements
from zope.interface.exceptions import InvalidInterface
from zope.interface.exceptions import BrokenImplementation
=== Added File Zope3/src/zope/interface/interfaces.py ===
##############################################################################
#
# Copyright (c) 2002 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.
#
##############################################################################
"""
$Id: interfaces.py,v 1.1.2.1 2002/12/23 19:32:54 jim Exp $
"""
from zope.interface import Interface
from zope.interface.interface import Attribute
class IElement(Interface):
"""Objects that have basic documentation and tagged values.
"""
__name__ = Attribute('__name__', 'The object name')
__doc__ = Attribute('__doc__', 'The object doc string')
def getName():
"""Returns the name of the object."""
def getDoc():
"""Returns the documentation for the object."""
def getTaggedValue(tag):
"""Returns the value associated with 'tag'."""
def getTaggedValueTags():
"""Returns a list of all tags."""
def setTaggedValue(tag, value):
"""Associates 'value' with 'key'."""
class IAttribute(IElement):
"""Attribute descriptors"""
class IMethod(IAttribute):
"""Method attributes
"""
# XXX What the heck should methods provide? Grrrr
def getSignatureString():
"""Return a signature string suitable for inclusion in documentation.
"""
class IInterface(IElement):
"""Interface objects
Interface objects describe the behavior of an object by containing
useful information about the object. This information includes:
o 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.
o Descriptions of attributes. Attribute descriptions include
the name of the attribute and prose documentation describing
the attributes usage.
o Descriptions of methods. Method descriptions can include:
o Prose "doc string" documentation about the method and its
usage.
o A description of the methods arguments; how many arguments
are expected, optional arguments and their default values,
the position or arguments in the signature, whether the
method accepts arbitrary arguments and whether the method
accepts arbitrary keyword arguments.
o Optional tagged data. Interface objects (and their attributes and
methods) can have optional, application specific tagged data
associated with them. Examples uses for this are examples,
security assertions, pre/post conditions, and other possible
information you may want to associate with an Interface or its
attributes.
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.
Interfaces are created with the Python class statement using
either Interface.Interface or another interface, as in::
from zope.interface import Interface
class IMyInterface(Interface):
'''Interface documentation
'''
def meth(arg1, arg2):
'''Documentation for meth
'''
# Note that there is no self argument
class IMySubInterface(IMyInterface):
'''Interface documentation
'''
def meth2():
'''Documentation for meth2
'''
You use interfaces in two ways:
o You assert that your object implement the interfaces.
There are several ways that you can assert that an object
implements an interface::
1. Include an '__implements__' attribute in the object's class
definition. The value of the '__implements__' attribute must
be an implementation specification. An implementation
specification is either an interface or a tuple of
implementation specifications.
2. Incluse an '__implements__' attribute in the object.
Because Python classes don't have their own attributes, to
assert that a class implements interfaces, you must provide a
'__class_implements__' attribute in the class definition.
**Important**: A class usually doesn't implement the
interfaces that its instances implement. The class and
its instances are separate objects with their own
interfaces.
3. Call 'Interface.Implements.implements' to assert that instances
of a class implement an interface.
For example::
from zope.interface.implements import implements
implements(some_class, some_interface)
This is approach is useful when it is not an option to modify
the class source. Note that this doesn't affect what the
class itself implements, but only what its instances
implement.
4. For types that can't be modified, you can assert that
instances of the type implement an interface using
'Interface.Implements.assertTypeImplements'.
For example::
from zope.interface.implements import assertTypeImplements
assertTypeImplements(some_type, some_interface)
o You query interface meta-data. See the IInterface methods and
attributes for details.
"""
def getBases():
"""Return a sequence of the base interfaces."""
def extends(other, strict=1):
"""Test whether the interface extends another interface
A true value is returned in the interface extends the other
interface, and false otherwise.
Normally, an interface doesn't extend itself. If a false value
is passed as the second argument, or via the 'strict' keyword
argument, then a true value will be returned if the interface
and the other interface are the same.
"""
def isImplementedBy(object):
"""Test whether the interface is implemented by the object
Return true of the object asserts that it implements the
interface, including asseting that it implements an extended
interface.
"""
def isImplementedByInstancesOf(class_):
"""Test whether the interface is implemented by instances of the class
Return true of the class asserts that its instances implement the
interface, including asseting that they implement an extended
interface.
"""
def names(all=0):
"""Get the interface attribute names
Return a sequence of the names of the attributes, including
methods, included in the interface definition.
Normally, only directly defined attributes are included. If
a true positional or keyword argument is given, then
attributes defined by nase classes will be included.
"""
def namesAndDescriptions(all=0):
"""Get the interface attribute names and descriptions
Return a sequence of the names and descriptions of the
attributes, including methods, as name-value pairs, included
in the interface definition.
Normally, only directly defined attributes are included. If
a true positional or keyword argument is given, then
attributes defined by nase classes will be included.
"""
def getDescriptionFor(name):
"""Get the description for a name
If the named attribute is not defined, a KeyError is raised.
"""
__getitem__ = getDescriptionFor
def queryDescriptionFor(name, default=None):
"""Look up the description for a name
If the named attribute is not defined, the default is
returned.
"""
get = queryDescriptionFor
def __contains__(name):
"""Test whether the name is defined by the interface"""
def __iter__():
"""Return an iterator over the names defined by the interface
The names iterated include all of the names defined by the
interface directly and indirectly by base interfaces.
"""
class ITypeRegistry(Interface):
"""Type-specific registry
This registry stores objects registered for objects that implement
a required interface.
"""
def register(require, object):
"""Register an object for a required interface.
The require argument may be None. This effectively defines a
default object.
"""
def get(implements, default=None):
"""Return a registered object
The registered object is one that was registered to require an
interface that one of the interfaces in the 'implements'
specification argument extends or equals. An attempt will be
made to find the component that most closely matches the input
arguments.
The object returned could have been registred to require None.
Note that the implements may be None, it which case a
component will be returned only if it was registered with a
require of None.
"""
def getAll(implements=None):
"""Get registered objects
Return all objects registered with a require interfaces such
that if the 'implements' argumennt is not None, it is an
implementation specification such that some of the interfaces
in the specification extend or equal the require interface (or
the require interface was None).
"""
def getAllForObject(object):
"""Get all registered objects for types that object implements.
"""
class IAdapterRegistry(Interface):
"""Adapter-style registry
This registry stores objects registered to convert (or participate
in the conversion from) one interface to another. The interface
converted is the "required" interface. We say that the interface
converted to is the "provided" interface.
The objects registered here don't need to be adapters. What's
important is that they are registered according to a required and
a provided interface.
The provided interface may not be None.
The required interface may be None. Adapters with a required
interface of None adapt non-components. An adapter that adapts all
components should specify a required interface of
Interface.Interface.
"""
def register(require, provide, object):
"""Register an object for a required and provided interface.
There are no restrictions on what the object might be.
Any restrictions (e.g. callability, or interface
implementation) must be enforced by higher-level code.
The require argument may be None.
"""
def get((implements, provides), default=None, filter=None):
"""Return a registered object
The registered object is one that was registered to require an
interface that one of the interfaces in the 'implements'
specification argument extends or equals and that provides an
interface that extends or equals the 'provides' argument. An
attempt will be made to find the component that most closely
matches the input arguments.
The object returned could have been registred to require None.
Note that the implements may be None, it which case a
component will be returned only if it was registered with a
require of None.
An optional filter may be provided. If provided, the returned
object must pass the filter. Search will continue until a
suitable match can be found. The filter should take a single
argument and return a true value if the object passes the
filter, or false otherwise.
"""
def getForObject(object, interface, filter=None):
"""Get an adapter for object that implements the specified interface
The filter option has the same meaning as in the get method.
"""
def getRegistered(require, provide):
"""return data registred specificly for the given interfaces
None is returned if nothing is registered.
"""
def getRegisteredMatching(required_interfaces=None,
provided_interfaces=None):
"""Return information about registered data
Zero or more required and provided interfaces may be
specified. Registration information matching any of the
specified interfaces is returned.
The arguments may be interfaces, or sequences of interfaces.
The returned value is a sequence of three-element tuples:
- required interface
- provided interface
- the object registered specifically for the required and
provided interfaces.
To understand hopw the matching works, imagine that we have
interfaces R1, R2, P1, and P2. R2 extends R1. P2 extends P1.
We've registered C to require R1 and provide P2. Given this,
if we call getRegisteredMatching:
registery.getRegisteredMatching([R2], [P1])
the returned value will include:
(R1, P2, C)
"""
class IImplementorRegistry(Interface):
"""Implementor registry
This registry stores objects registered to implement (or help
implement) an interface. For example, this registry could be used
to register utilities.
The objects registered here don't need to be implementors. (They
might just be useful to implementation.) What's important is that
they are registered according to a provided interface.
"""
def register(provide, object):
"""Register an object for a required and provided interface.
There are no restrictions on what the object might be.
Any restrictions (e.g. callability, or interface
implementation) must be enforced by higher-level code.
The require argument may be None.
"""
def get(provides, default=None):
"""Return a registered object
The registered object is one that was registered that provides an
interface that extends or equals the 'provides' argument.
"""
=== Added File Zope3/src/zope/interface/pyskel.py ===
#!/usr/bin/env python
##############################################################################
#
# Copyright (c) 2001, 2002 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.
#
##############################################################################
"""
Generate method skeletons for intefaces.
Usage: python pyskel.py dotted_name
Example:
cd lib/python
python Interface/pyskel.py Zope.App.Security.IRoleService.IRoleService
The dotted name is the module name and interface object name connected
with a dot.
Revision information: $Id: pyskel.py,v 1.1.2.1 2002/12/23 19:32:54 jim Exp $
"""
import sys, os, re
sys.path.insert(0, os.getcwd())
from types import ModuleType
from zope.interface.element import Method
from zope.interface.element import Attribute
class_re = re.compile(r'\s*class\s+([a-zA-Z_][a-zA-Z0-9_]*)')
def_re = re.compile(r'\s*def\s+([a-zA-Z_][a-zA-Z0-9_]*)')
attr_re = re.compile(r'\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*Attribute')
def rskel(iface, top, print_iface=1):
name = "%s.%s" % (iface.__module__, iface.__name__)
file = resolve(iface.__module__).__file__
if file.endswith('pyc'):
file = file[:-1]
order = guessOrder(open(file))
namesAndDescriptions = getAttributesInOrder(iface, order)
namesAndDescriptions = filter(lambda ades:
isinstance(ades[1], Method) or
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]
if sig: sig = "self, %s" % sig
else: sig = "self"
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
print " # See %s" % name
print " %s = None" %aname
else:
print
print 'Waaaa', ades
for base in iface.__bases__:
if base.__name__ not in ('Interface',):
rskel(base, top)
def skel(name):
iface = resolve(name)
class_name = iface.__name__
if class_name.startswith('I'):
class_name = class_name[1:]
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
# print " ############################################################"
# print " # Implementation methods for interface"
# print " #", name
rskel(iface, iface, 0)
# print
# print " #"
# print " ############################################################"
def resolve(name, _silly=('__doc__',), _globals={}):
# Support for file path syntax; this way I can use TAB to search for
# the module.
if '/' in name or name.endswith('.py'):
# We got a relative path. Let's try to get the full one and then
# make a package path out of it.
if not name.startswith('/'):
cwd = os.getcwd()
for path in sys.path[1:]: # Yeah, we need to exclude the cwd itself
if path != '' and cwd.startswith(path):
name = os.path.join(cwd[len(path)+1:], name)
name = os.path.normpath(name)
break
# get rid of the file ending :)
if name.endswith('.py'):
name = name[:-3]
name = name.replace('/', '.')
# Now to the regular lookup
if name[:1]=='.':
name='ZopeProducts'+name
if name[-1:] == '.':
name = name[:-1]
repeat = 1
else:
repeat = 0
names=name.split('.')
last=names[-1]
mod='.'.join(names[:-1])
while 1:
m=__import__(mod, _globals, _globals, _silly)
try:
a=getattr(m, last)
except AttributeError:
pass
else:
if not repeat or (type(a) is not ModuleType):
return a
mod += '.' + last
def guessOrder(source_file):
order = {} # { class name -> list of methods }
lines = source_file.readlines()
class_name = None
for line in lines:
m = class_re.match(line)
if m and m.groups():
class_name = m.groups()[0]
else:
for m in (def_re.match(line),
attr_re.match(line)):
if m and m.groups():
def_name = m.groups()[0]
name_order = order.get(class_name)
if name_order is None:
name_order = []
order[class_name] = name_order
name_order.append(def_name)
return order
def getAttributesInOrder(interface, order):
# order is the dictionary returned from guessOrder().
# interface is a metaclass-based interface object.
name_order = order.get(interface.__name__)
if name_order is None:
# Something's wrong. Oh well.
items = interface.namesAndDescriptions()
items.sort()
return items
else:
items = []
for key, value in interface.namesAndDescriptions():
if key in name_order:
items.append((name_order.index(key), key, value))
else:
items.append((99999, key, value)) # Go to end.
items.sort()
return map(lambda item: item[1:], items)
if __name__ == '__main__':
for a in sys.argv[1:]:
skel(a)
=== Added File Zope3/src/zope/interface/type.py ===
##############################################################################
#
# Copyright (c) 2002 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.
#
##############################################################################
"""Adapter-style interface registry
See Adapter class.
$Id: type.py,v 1.1.2.1 2002/12/23 19:32:54 jim Exp $
"""
__metaclass__ = type # All classes are new style when run with Python 2.2+
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.interface._flatten import _flatten
from zope.interface.interfaces import ITypeRegistry
class TypeRegistry:
__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,
# I'm not sure what the last sentence is trying to say :-).
# The implementation uses a mapping:
#
# { (required_interface, provided_interface) ->
# (registered_provides, component) }
#
# Where the registered provides is what was registered and
# provided may be some base interface
def __init__(self):
self._reg = {}
def register(self, interface, object):
if interface is not None and not IInterface.isImplementedBy(interface):
raise TypeError(
"The interface argument must be an interface (or None)")
self._reg[interface] = object
def get(self, interface, default=None):
"""
Finds a registered component that provides the given interface.
Returns None if not found.
"""
return self._reg.get(interface, default)
def setdefault(self, interface, default=None):
return self._reg.setdefault(interface, default)
def getAll(self, interface_spec):
result = []
for interface in _flatten(interface_spec):
object = self._reg.get(interface)
if object is not None:
result.append(object)
if interface_spec is not None:
object = self._reg.get(None)
if object is not None:
result.append(object)
return result
def getAllForObject(self, object):
# XXX This isn't quite right, since it doesn't take into
# account implementation registries for objects that can't
# have '__implements__' attributes.
return self.getAll(getattr(object, '__implements__', None))
=== Added File Zope3/src/zope/interface/verify.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 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.
#
##############################################################################
from zope.interface.exceptions import BrokenImplementation, DoesNotImplement
from zope.interface.exceptions import BrokenMethodImplementation
from types import FunctionType, MethodType
from zope.interface.interface import fromMethod, fromFunction
def _verify(iface, candidate, tentative=0, vtype=None):
"""Verify that 'candidate' might correctly implements 'iface'.
This involves:
o Making sure the candidate defines all the necessary methods
o Making sure the methods have the correct signature
o Making sure the candidate asserts that it implements the interface
Note that this isn't the same as verifying that the class does
implement the interface.
If optional tentative is true, suppress the "is implemented by" test.
"""
if vtype == 'c':
tester = iface.isImplementedByInstancesOf
else:
tester = iface.isImplementedBy
if not tentative and not tester( candidate ):
raise DoesNotImplement(iface)
for n, d in iface.namesAndDescriptions(1):
if not hasattr(candidate, n):
raise BrokenImplementation(iface, n)
attr = getattr(candidate, n)
if type(attr) is FunctionType:
# should never get here
meth = fromFunction(attr, n)
elif type(attr) is MethodType:
meth = fromMethod(attr, n)
else:
continue # must be an attribute...
d=d.getSignatureInfo()
meth = meth.getSignatureInfo()
mess = _incompat(d, meth)
if mess:
raise BrokenMethodImplementation(n, mess)
return 1
def verifyClass(iface, candidate, tentative=0):
return _verify(iface, candidate, tentative, vtype='c')
def verifyObject(iface, candidate, tentative=0):
return _verify(iface, candidate, tentative, vtype='o')
def _incompat(required, implemented):
#if (required['positional'] !=
# implemented['positional'][:len(required['positional'])]
# and implemented['kwargs'] is None):
# return 'imlementation has different argument names'
if len(implemented['required']) > len(required['required']):
return 'implementation requires too many arguments'
if ((len(implemented['positional']) < len(required['positional']))
and not implemented['varargs']):
return "implementation doesn't allow enough arguments"
if required['kwargs'] and not implemented['kwargs']:
return "implementation doesn't support keyword arguments"
if required['varargs'] and not implemented['varargs']:
return "implementation doesn't support variable arguments"