Learn more  » Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

aroundthecode / zope.interface   python

Repository URL to install this package:

Version: 4.6.0 

/ interface / declarations.py

##############################################################################
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (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.
##############################################################################
"""Implementation of interface declarations

There are three flavors of declarations:

  - Declarations are used to simply name declared interfaces.

  - ImplementsDeclarations are used to express the interfaces that a
    class implements (that instances of the class provides).

    Implements specifications support inheriting interfaces.

  - ProvidesDeclarations are used to express interfaces directly
    provided by objects.

"""
__docformat__ = 'restructuredtext'

import sys
from types import FunctionType
from types import MethodType
from types import ModuleType
import weakref

from zope.interface.advice import addClassAdvisor
from zope.interface.interface import InterfaceClass
from zope.interface.interface import SpecificationBase
from zope.interface.interface import Specification
from zope.interface._compat import CLASS_TYPES as DescriptorAwareMetaClasses
from zope.interface._compat import PYTHON3

# Registry of class-implementation specifications
BuiltinImplementationSpecifications = {}

_ADVICE_ERROR = ('Class advice impossible in Python3.  '
                 'Use the @%s class decorator instead.')

_ADVICE_WARNING = ('The %s API is deprecated, and will not work in Python3  '
                   'Use the @%s class decorator instead.')

class named(object):

    def __init__(self, name):
        self.name = name

    def __call__(self, ob):
        ob.__component_name__ = self.name
        return ob

class Declaration(Specification):
    """Interface declarations"""

    def __init__(self, *interfaces):
        Specification.__init__(self, _normalizeargs(interfaces))

    def changed(self, originally_changed):
        Specification.changed(self, originally_changed)
        try:
            del self._v_attrs
        except AttributeError:
            pass

    def __contains__(self, interface):
        """Test whether an interface is in the specification
        """

        return self.extends(interface) and interface in self.interfaces()

    def __iter__(self):
        """Return an iterator for the interfaces in the specification
        """
        return self.interfaces()

    def flattened(self):
        """Return an iterator of all included and extended interfaces
        """
        return iter(self.__iro__)

    def __sub__(self, other):
        """Remove interfaces from a specification
        """
        return Declaration(
            *[i for i in self.interfaces()
                if not [j for j in other.interfaces()
                        if i.extends(j, 0)]
                ]
                )

    def __add__(self, other):
        """Add two specifications or a specification and an interface
        """
        seen = {}
        result = []
        for i in self.interfaces():
            seen[i] = 1
            result.append(i)
        for i in other.interfaces():
            if i not in seen:
                seen[i] = 1
                result.append(i)

        return Declaration(*result)

    __radd__ = __add__


##############################################################################
#
# Implementation specifications
#
# These specify interfaces implemented by instances of classes

class Implements(Declaration):

    # class whose specification should be used as additional base
    inherit = None

    # interfaces actually declared for a class
    declared = ()

    __name__ = '?'

    @classmethod
    def named(cls, name, *interfaces):
        # Implementation method: Produce an Implements interface with
        # a fully fleshed out __name__ before calling the constructor, which
        # sets bases to the given interfaces and which may pass this object to
        # other objects (e.g., to adjust dependents). If they're sorting or comparing
        # by name, this needs to be set.
        inst = cls.__new__(cls)
        inst.__name__ = name
        inst.__init__(*interfaces)
        return inst

    def __repr__(self):
        return '<implementedBy %s>' % (self.__name__)

    def __reduce__(self):
        return implementedBy, (self.inherit, )

    def __cmp(self, other):
        # Yes, I did mean to name this __cmp, rather than __cmp__.
        # It is a private method used by __lt__ and __gt__.
        # This is based on, and compatible with, InterfaceClass.
        # (The two must be mutually comparable to be able to work in e.g., BTrees.)
        # Instances of this class generally don't have a __module__ other than
        # `zope.interface.declarations`, whereas they *do* have a __name__ that is the
        # fully qualified name of the object they are representing.

        # Note, though, that equality and hashing are still identity based. This
        # accounts for things like nested objects that have the same name (typically
        # only in tests) and is consistent with pickling. As far as comparisons to InterfaceClass
        # goes, we'll never have equal name and module to those, so we're still consistent there.
        # Instances of this class are essentially intended to be unique and are
        # heavily cached (note how our __reduce__ handles this) so having identity
        # based hash and eq should also work.
        if other is None:
            return -1

        n1 = (self.__name__, self.__module__)
        n2 = (getattr(other, '__name__', ''), getattr(other,  '__module__', ''))

        # This spelling works under Python3, which doesn't have cmp().
        return (n1 > n2) - (n1 < n2)

    def __hash__(self):
        return Declaration.__hash__(self)

    # We want equality to be based on identity. However, we can't actually
    # implement __eq__/__ne__ to do this because sometimes we get wrapped in a proxy.
    # We need to let the proxy types implement these methods so they can handle unwrapping
    # and then rely on: (1) the interpreter automatically changing `implements == proxy` into
    # `proxy == implements` (which will call proxy.__eq__ to do the unwrapping) and then
    # (2) the default equality semantics being identity based.

    def __lt__(self, other):
        c = self.__cmp(other)
        return c < 0

    def __le__(self, other):
        c = self.__cmp(other)
        return c <= 0

    def __gt__(self, other):
        c = self.__cmp(other)
        return c > 0

    def __ge__(self, other):
        c = self.__cmp(other)
        return c >= 0

def _implements_name(ob):
    # Return the __name__ attribute to be used by its __implemented__
    # property.
    # This must be stable for the "same" object across processes
    # because it is used for sorting. It needn't be unique, though, in cases
    # like nested classes named Foo created by different functions, because
    # equality and hashing is still based on identity.
    # It might be nice to use __qualname__ on Python 3, but that would produce
    # different values between Py2 and Py3.
    return (getattr(ob, '__module__', '?') or '?') + \
        '.' + (getattr(ob, '__name__', '?') or '?')

def implementedByFallback(cls):
    """Return the interfaces implemented for a class' instances

      The value returned is an `~zope.interface.interfaces.IDeclaration`.
    """
    try:
        spec = cls.__dict__.get('__implemented__')
    except AttributeError:

        # we can't get the class dict. This is probably due to a
        # security proxy.  If this is the case, then probably no
        # descriptor was installed for the class.

        # We don't want to depend directly on zope.security in
        # zope.interface, but we'll try to make reasonable
        # accommodations in an indirect way.

        # We'll check to see if there's an implements:

        spec = getattr(cls, '__implemented__', None)
        if spec is None:
            # There's no spec stred in the class. Maybe its a builtin:
            spec = BuiltinImplementationSpecifications.get(cls)
            if spec is not None:
                return spec
            return _empty

        if spec.__class__ == Implements:
            # we defaulted to _empty or there was a spec. Good enough.
            # Return it.
            return spec

        # TODO: need old style __implements__ compatibility?
        # Hm, there's an __implemented__, but it's not a spec. Must be
        # an old-style declaration. Just compute a spec for it
        return Declaration(*_normalizeargs((spec, )))

    if isinstance(spec, Implements):
        return spec

    if spec is None:
        spec = BuiltinImplementationSpecifications.get(cls)
        if spec is not None:
            return spec

    # TODO: need old style __implements__ compatibility?
    spec_name = _implements_name(cls)
    if spec is not None:
        # old-style __implemented__ = foo declaration
        spec = (spec, ) # tuplefy, as it might be just an int
        spec = Implements.named(spec_name, *_normalizeargs(spec))
        spec.inherit = None    # old-style implies no inherit
        del cls.__implemented__ # get rid of the old-style declaration
    else:
        try:
            bases = cls.__bases__
        except AttributeError:
            if not callable(cls):
                raise TypeError("ImplementedBy called for non-factory", cls)
            bases = ()

        spec = Implements.named(spec_name, *[implementedBy(c) for c in bases])
        spec.inherit = cls

    try:
        cls.__implemented__ = spec
        if not hasattr(cls, '__providedBy__'):
            cls.__providedBy__ = objectSpecificationDescriptor

        if (isinstance(cls, DescriptorAwareMetaClasses)
            and
            '__provides__' not in cls.__dict__):
            # Make sure we get a __provides__ descriptor
            cls.__provides__ = ClassProvides(
                cls,
                getattr(cls, '__class__', type(cls)),
                )

    except TypeError:
        if not isinstance(cls, type):
            raise TypeError("ImplementedBy called for non-type", cls)
        BuiltinImplementationSpecifications[cls] = spec

    return spec

implementedBy = implementedByFallback

def classImplementsOnly(cls, *interfaces):
    """Declare the only interfaces implemented by instances of a class

      The arguments after the class are one or more interfaces or interface
      specifications (`~zope.interface.interfaces.IDeclaration` objects).

      The interfaces given (including the interfaces in the specifications)
      replace any previous declarations.
    """
    spec = implementedBy(cls)
    spec.declared = ()
    spec.inherit = None
    classImplements(cls, *interfaces)

def classImplements(cls, *interfaces):
    """Declare additional interfaces implemented for instances of a class

      The arguments after the class are one or more interfaces or
      interface specifications (`~zope.interface.interfaces.IDeclaration` objects).

      The interfaces given (including the interfaces in the specifications)
      are added to any interfaces previously declared.
    """
    spec = implementedBy(cls)
    spec.declared += tuple(_normalizeargs(interfaces))

    # compute the bases
    bases = []
    seen = {}
    for b in spec.declared:
        if b not in seen:
            seen[b] = 1
            bases.append(b)

    if spec.inherit is not None:

        for c in spec.inherit.__bases__:
            b = implementedBy(c)
            if b not in seen:
                seen[b] = 1
                bases.append(b)

    spec.__bases__ = tuple(bases)

def _implements_advice(cls):
Loading ...