Esempio n. 1
0
    def factory_py2(regex):
        from zope.interface.advice import addClassAdvisor
        _f = {}

        def decorator(f):
            _f[f.__name__] = f
            return f

        def advisor(cls):
            def wrapped(f):
                def __init__(self, *args, **kwargs):
                    f(self, *args, **kwargs)
                    func = None
                    orig = None
                    for func_name in _f:
                        orig = _f[func_name]
                        func = getattr(self, func_name)
                    if orig and func and func.im_func == orig:
                        self.register(method, regex, func)

                return __init__

            cls.__init__ = wrapped(cls.__init__)
            return cls

        addClassAdvisor(advisor)
        return decorator
Esempio n. 2
0
 def __init__(self, field_name, widget, *args, **kwargs):
     self.field_name = field_name
     if widget is None:
         self.widget = None
     else:
         self.widget = CustomWidgetFactory(widget, *args, **kwargs)
     addClassAdvisor(self.advise)
def ping(log, value):

    def pong(klass):
        log.append((value,klass))
        return [klass]

    addClassAdvisor(pong)
Esempio n. 4
0
def kindInfo(**attrs):
    """Declare metadata for a class' schema item

    The attributes defined by the keyword arguments will be set on the
    enclosing class' schema Item.  For example, the following class'
    repository Kind will have a ``displayName`` of ``"Example Item"``, and
    a ``displayAttribute`` of ``"someAttr"``::

        class SomeItem(schema.Item):
            schema.kindInfo(
                displayName = "Example Item",
                displayAttribute = "someAttr",
            )

    ``kindInfo()`` can only be used in the body of a class that derives from
    ``schema.Item`` or ``schema.Enumeration``, and it will only accept keywords
    that are valid attributes of the ``Kind`` or ``Enumeration`` kinds,
    respectively.

    (Note: if your class includes a ``__metaclass__`` definition, any calls to
    ``kindInfo`` must come *after* the ``__metaclass__`` assignment.)
    """
    _update_info('kindInfo','__kind_info__',attrs)

    def callback(cls):
        for k,v in attrs.items():
            if not hasattr(cls._kind_class, k):
                raise TypeError(
                    "%r is not an attribute of %s" %
                    (k, cls._kind_class.__name__)
                )
        return cls

    from zope.interface.advice import addClassAdvisor
    addClassAdvisor(callback)
 def __init__(self, field_name, widget, *args, **kwargs):
     self.field_name = field_name
     if widget is None:
         self.widget = None
     else:
         self.widget = CustomWidgetFactory(widget, *args, **kwargs)
     addClassAdvisor(self.advise)
Esempio n. 6
0
def strictly_implements(*interfaces):
    frame = sys._getframe(1)
    f_locals = frame.f_locals

    # Try to make sure we were called from a class def. Assumes Python > 2.2.
    if f_locals is frame.f_globals or '__module__' not in f_locals:
        raise TypeError("implements can be used only from a class definition.")

    if '__implements_advice_data__' in f_locals:
        raise TypeError(
            "implements can be used only once in a class definition.")

    def _implements_advice(cls):
        interfaces, classImplements = cls.__dict__[
            '__implements_advice_data__']
        del cls.__implements_advice_data__
        classImplements(cls, *interfaces)

        if interesting_modules.match(cls.__module__):
            if not excluded_classnames.match(cls.__name__):
                for interface in interfaces:
                    try:
                        verifyClass(interface, cls)
                    except Exception as e:
                        print("%s.%s does not correctly implement %s.%s:\n%s" %
                              (cls.__module__, cls.__name__,
                               interface.__module__, interface.__name__, e),
                              file=_err)
        else:
            _other_modules_with_violations.add(cls.__module__)
        return cls

    f_locals['__implements_advice_data__'] = interfaces, zi.classImplements
    addClassAdvisor(_implements_advice, depth=2)
Esempio n. 7
0
def strictly_implements(*interfaces):
    frame = sys._getframe(1)
    f_locals = frame.f_locals

    # Try to make sure we were called from a class def. Assumes Python > 2.2.
    if f_locals is frame.f_globals or '__module__' not in f_locals:
        raise TypeError("implements can be used only from a class definition.")

    if '__implements_advice_data__' in f_locals:
        raise TypeError("implements can be used only once in a class definition.")

    def _implements_advice(cls):
        interfaces, classImplements = cls.__dict__['__implements_advice_data__']
        del cls.__implements_advice_data__
        classImplements(cls, *interfaces)

        if interesting_modules.match(cls.__module__):
            if not excluded_classnames.match(cls.__name__):
                for interface in interfaces:
                    try:
                        verifyClass(interface, cls)
                    except Exception as e:
                        print("%s.%s does not correctly implement %s.%s:\n%s"
                                       % (cls.__module__, cls.__name__,
                                          interface.__module__, interface.__name__, e), file=_err)
        else:
            _other_modules_with_violations.add(cls.__module__)
        return cls

    f_locals['__implements_advice_data__'] = interfaces, zi.classImplements
    addClassAdvisor(_implements_advice, depth=2)
Esempio n. 8
0
 def __init__(self, arg1, arg2=None, status=None):
     if arg2 is None:
         self.fromname = None
         self.toname = arg1
     else:
         self.fromname = arg1
         self.toname = lambda self: arg2
         addClassAdvisor(self.advise)
     self.status = status
Esempio n. 9
0
    def __call__(self, fn):
        # We are being used as a descriptor.
        assert self.fromname is None, (
            "redirection() can not be used as a descriptor in its "
            "two argument form")

        self.fromname = self.toname
        self.toname = fn
        addClassAdvisor(self.advise)

        return fn
Esempio n. 10
0
def implements(*ifaces):
    """
    This is a slight hack, it overrides the default zope.interface implements
    function because it to uses the addClassAdvisor functionality to delay its
    work till after the class is created.  So we must as well, and by placing
    our hook in here we avoid the client having to manually add it.
    """
    declarations._implements("implements", ifaces, _classImplements)

    # These are called after the class that
    advice.addClassAdvisor(_register_class)
    advice.addClassAdvisor(_verify_class)
Esempio n. 11
0
def implements(*ifaces):
    """
    This is a slight hack, it overrides the default zope.interface implements
    function because it to uses the addClassAdvisor functionality to delay its
    work till after the class is created.  So we must as well, and by placing
    our hook in here we avoid the client having to manually add it.
    """
    declarations._implements("implements", ifaces, _classImplements)

    # These are called after the class that
    advice.addClassAdvisor(_register_class)
    advice.addClassAdvisor(_verify_class)
Esempio n. 12
0
def _implements(name, interfaces, classImplements):
    frame = sys._getframe(2)
    locals = frame.f_locals

    # Try to make sure we were called from a class def
    if (locals is frame.f_globals) or ('__module__' not in locals):
        raise TypeError(name+" can be used only from a class definition.")

    if '__implements_advice_data__' in locals:
        raise TypeError(name+" can be used only once in a class definition.")

    locals['__implements_advice_data__'] = interfaces, classImplements
    addClassAdvisor(_implements_advice, depth=3)
Esempio n. 13
0
def delegates(interface_spec, context='context'):
    """Make an adapter into a decorator.

    Use like:

        class RosettaProject:
            implements(IRosettaProject)
            delegates(IProject)

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

            def methodFromRosettaProject(self):
                return self.context.methodFromIProject()

    If you want to use a different name than "context" then you can explicitly
    say so:

        class RosettaProject:
            implements(IRosettaProject)
            delegates(IProject, context='project')

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

            def methodFromRosettaProject(self):
                return self.project.methodFromIProject()

    The adapter class will implement the interface it is decorating.

    The minimal decorator looks like this:

    class RosettaProject:
        delegates(IProject)

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

    """
    # pylint: disable-msg=W0212
    frame = sys._getframe(1)
    locals = frame.f_locals

    # Try to make sure we were called from a class def
    if (locals is frame.f_globals) or ('__module__' not in locals):
        raise TypeError(
            "delegates() can be used only from a class definition.")

    locals['__delegates_advice_data__'] = interface_spec, context
    addClassAdvisor(_delegates_advice, depth=2)
Esempio n. 14
0
def delegates(interface_spec, context='context'):
    """Make an adapter into a decorator.

    Use like:

        class RosettaProject:
            implements(IRosettaProject)
            delegates(IProject)

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

            def methodFromRosettaProject(self):
                return self.context.methodFromIProject()

    If you want to use a different name than "context" then you can explicitly
    say so:

        class RosettaProject:
            implements(IRosettaProject)
            delegates(IProject, context='project')

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

            def methodFromRosettaProject(self):
                return self.project.methodFromIProject()

    The adapter class will implement the interface it is decorating.

    The minimal decorator looks like this:

    class RosettaProject:
        delegates(IProject)

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

    """
    # pylint: disable-msg=W0212
    frame = sys._getframe(1)
    locals = frame.f_locals

    # Try to make sure we were called from a class def
    if (locals is frame.f_globals) or ('__module__' not in locals):
        raise TypeError(
            "delegates() can be used only from a class definition.")

    locals['__delegates_advice_data__'] = interface_spec, context
    addClassAdvisor(_delegates_advice, depth=2)
Esempio n. 15
0
def classProvides(*interfaces):
    """Declare interfaces provided directly by a class

      This function is called in a class definition.

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

      The given interfaces (including the interfaces in the specifications)
      are used to create the class's direct-object interface specification.
      An error will be raised if the module class has an direct interface
      specification. In other words, it is an error to call this function more
      than once in a class definition.

      Note that the given interfaces have nothing to do with the interfaces
      implemented by instances of the class.

      This function is provided for convenience. It provides a more convenient
      way to call `directlyProvides` for a class. For example::

        classProvides(I1)

      is equivalent to calling::

        directlyProvides(theclass, I1)

      after the class has been created.
    """
    # This entire approach is invalid under Py3K.  Don't even try to fix
    # the coverage for this block there. :(

    if PYTHON3:
        raise TypeError(_ADVICE_ERROR % 'provider')

    frame = sys._getframe(1)
    locals = frame.f_locals

    # Try to make sure we were called from a class def
    if (locals is frame.f_globals) or ('__module__' not in locals):
        raise TypeError("classProvides can be used only from a "
                        "class definition.")

    if '__provides__' in locals:
        raise TypeError(
            "classProvides can only be used once in a class definition.")

    locals["__provides__"] = _normalizeargs(interfaces)

    addClassAdvisor(_classProvides_advice, depth=2)
Esempio n. 16
0
def classProvides(*interfaces):
    """Declare interfaces provided directly by a class

      This function is called in a class definition.

      The arguments are one or more interfaces or interface specifications
      (``IDeclaration`` objects).

      The given interfaces (including the interfaces in the specifications)
      are used to create the class's direct-object interface specification.
      An error will be raised if the module class has an direct interface
      specification. In other words, it is an error to call this function more
      than once in a class definition.

      Note that the given interfaces have nothing to do with the interfaces
      implemented by instances of the class.

      This function is provided for convenience. It provides a more convenient
      way to call directlyProvides for a class. For example::

        classProvides(I1)

      is equivalent to calling::

        directlyProvides(theclass, I1)

      after the class has been created.
    """
    # This entire approach is invalid under Py3K.  Don't even try to fix
    # the coverage for this block there. :(
                       
    if PYTHON3: #pragma NO COVER
        raise TypeError(_ADVICE_ERROR % 'provider')

    frame = sys._getframe(1)
    locals = frame.f_locals

    # Try to make sure we were called from a class def
    if (locals is frame.f_globals) or ('__module__' not in locals):
        raise TypeError("classProvides can be used only from a "
                        "class definition.")

    if '__provides__' in locals:
        raise TypeError(
            "classProvides can only be used once in a class definition.")

    locals["__provides__"] = _normalizeargs(interfaces)

    addClassAdvisor(_classProvides_advice, depth=2)
Esempio n. 17
0
def _implements(name, interfaces, classImplements):
    frame = sys._getframe(2)
    locals = frame.f_locals

    # Try to make sure we were called from a class def. In 2.2.0 we can't
    # check for __module__ since it doesn't seem to be added to the locals
    # until later on.
    if (locals is frame.f_globals) or (
        ('__module__' not in locals) and sys.version_info[:3] > (2, 2, 0)):
        raise TypeError(name+" can be used only from a class definition.")

    if '__implements_advice_data__' in locals:
        raise TypeError(name+" can be used only once in a class definition.")

    locals['__implements_advice_data__'] = interfaces, classImplements
    addClassAdvisor(_implements_advice, depth=3)
Esempio n. 18
0
def _implements(name, interfaces, classImplements):
    frame = sys._getframe(2)
    locals = frame.f_locals

    # Try to make sure we were called from a class def. In 2.2.0 we can't
    # check for __module__ since it doesn't seem to be added to the locals
    # until later on.
    if (locals is frame.f_globals) or (('__module__' not in locals)
                                       and sys.version_info[:3] > (2, 2, 0)):
        raise TypeError(name + " can be used only from a class definition.")

    if '__implements_advice_data__' in locals:
        raise TypeError(name + " can be used only once in a class definition.")

    locals['__implements_advice_data__'] = interfaces, classImplements
    addClassAdvisor(_implements_advice, depth=3)
Esempio n. 19
0
def _implements(name, interfaces, classImplements):
    # This entire approach is invalid under Py3K.  Don't even try to fix
    # the coverage for this block there. :(
    frame = sys._getframe(2)
    locals = frame.f_locals

    # Try to make sure we were called from a class def. In 2.2.0 we can't
    # check for __module__ since it doesn't seem to be added to the locals
    # until later on.
    if locals is frame.f_globals or '__module__' not in locals:
        raise TypeError(name + " can be used only from a class definition.")

    if '__implements_advice_data__' in locals:
        raise TypeError(name + " can be used only once in a class definition.")

    locals['__implements_advice_data__'] = interfaces, classImplements
    addClassAdvisor(_implements_advice, depth=3)
Esempio n. 20
0
def _implements(name, interfaces, classImplements):
    # This entire approach is invalid under Py3K.  Don't even try to fix
    # the coverage for this block there. :(
    frame = sys._getframe(2)
    locals = frame.f_locals

    # Try to make sure we were called from a class def. In 2.2.0 we can't
    # check for __module__ since it doesn't seem to be added to the locals
    # until later on.
    if locals is frame.f_globals or '__module__' not in locals:
        raise TypeError(name+" can be used only from a class definition.")

    if '__implements_advice_data__' in locals:
        raise TypeError(name+" can be used only once in a class definition.")

    locals['__implements_advice_data__'] = interfaces, classImplements
    addClassAdvisor(_implements_advice, depth=3)
Esempio n. 21
0
def instanceClassOf(typeClass):
    """Signal that the class suite is an instance factory for the
    specified protocol class.

    The instance class must have a constructor that accepts no arguments.
    """
    def callback(instanceClass):
        class InstanceFactory:
            def __init__(self, protocolClass):
                pass
            def buildInstance(self):
                return instanceClass()
        components.registerAdapter(InstanceFactory, typeClass, 
                                   igwt.IInstanceFactory)
        annotation.registerTypeAdapter(typeClass, instanceClass)
        return instanceClass
    advice.addClassAdvisor(callback)
Esempio n. 22
0
    def _advice(name, callback,  data, depth=3 ):
        frame = sys._getframe(depth-1)
        locals = frame.f_locals

        if (locals is frame.f_globals) or (
            ('__module__' not in locals) and sys.version_info[:3] > (2, 2, 0)):
            raise SyntaxError("%s can be used only from a class definition." % name)

        if not '__advice_data__' in locals:
            locals['__advice_data__'] = {}

        if name in locals['__advice_data__']:
            raise SyntaxError("%s can be used only once in a class definition." % name)


        if not locals['__advice_data__']:
            addClassAdvisor(_callback, depth=depth)

        locals['__advice_data__'][name] = (data, callback)
Esempio n. 23
0
 def factory(regex):
     _f = {}
     def decorator(f):
         _f[f.__name__] = f
         return f
     def advisor(cls):
         def wrapped(f):
             def __init__(self, *args, **kwargs):
                 f(self, *args, **kwargs)
                 for func_name in _f:
                     orig = _f[func_name]
                     func = getattr(self, func_name)
                 if func.im_func==orig:
                     self.register(method, regex, func)
             return __init__
         cls.__init__ = wrapped(cls.__init__)
         return cls
     addClassAdvisor(advisor)
     return decorator
Esempio n. 24
0
def dependsOn(itemType,
              itemCustomizer=None,
              doc='',
              indexed=True,
              whenDeleted=reference.NULLIFY):
    """
    This function behaves like L{axiom.attributes.reference} but with
    an extra behaviour: when this item is installed (via
    L{axiom.dependency.installOn} on a target item, the
    type named here will be instantiated and installed on the target
    as well.

    For example::

      class Foo(Item):
          counter = integer()
          thingIDependOn = dependsOn(Baz, lambda baz: baz.setup())

    @param itemType: The Item class to instantiate and install.
    @param itemCustomizer: A callable that accepts the item installed
    as a dependency as its first argument. It will be called only if
    an item is created to satisfy this dependency.

    @return: An L{axiom.attributes.reference} instance.
    """

    frame = sys._getframe(1)
    locals = frame.f_locals

    # Try to make sure we were called from a class def.
    if (locals is frame.f_globals) or ('__module__' not in locals):
        raise TypeError("dependsOn can be used only from a class definition.")
    ref = reference(reftype=itemType,
                    doc=doc,
                    indexed=indexed,
                    allowNone=True,
                    whenDeleted=whenDeleted)
    if "__dependsOn_advice_data__" not in locals:
        addClassAdvisor(_dependsOn_advice)
    locals.setdefault('__dependsOn_advice_data__', []).append(
        (itemType, itemCustomizer, ref))
    return ref
Esempio n. 25
0
def _implements(name, args, kw, classImplements):

    #NOTE: str(classImplements) в данном случае используется просто в качестве уникального идентификатора

    def _implements_advice(cls):
        classImplements(cls, *args, **kw)
        return cls

    frame = sys._getframe(2)
    locals = frame.f_locals
    # Try to make sure we were called from a class def. In 2.2.0 we can't
    # check for __module__ since it doesn't seem to be added to the locals
    # until later on.
    if (locals is frame.f_globals) or (
        ('__module__' not in locals) and sys.version_info[:3] > (2, 2, 0)):
        raise TypeError(name+" can be used only from a class definition.")
    if str(classImplements) in locals:
        raise TypeError(name+" can be used only once in a class definition.")
    locals[str(classImplements)] = args, kw, classImplements
    addClassAdvisor(_implements_advice, depth=3)
Esempio n. 26
0
def view(name, *args, **kwargs):
    """
    This will attach a view to the controller.
    
    This should be used from within a class such as:
    
    >>> class MyController(Controller):
    ...     view('main')
    ...
    >>>
    
    @name: the name of the view such as 'main'
    """
    action = (_view, (name,) + args, kwargs)
    def installAction(cls):
        if not hasattr(cls, '_lift_items'):
            cls._lift_items = []
        cls._lift_items.append(action)
        return cls
    addClassAdvisor(installAction)
Esempio n. 27
0
def dependsOn(itemType, itemCustomizer=None, doc='',
              indexed=True, whenDeleted=reference.NULLIFY):
    """
    This function behaves like L{axiom.attributes.reference} but with
    an extra behaviour: when this item is installed (via
    L{axiom.dependency.installOn} on a target item, the
    type named here will be instantiated and installed on the target
    as well.

    For example::

      class Foo(Item):
          counter = integer()
          thingIDependOn = dependsOn(Baz, lambda baz: baz.setup())

    @param itemType: The Item class to instantiate and install.
    @param itemCustomizer: A callable that accepts the item installed
    as a dependency as its first argument. It will be called only if
    an item is created to satisfy this dependency.

    @return: An L{axiom.attributes.reference} instance.
    """

    frame = sys._getframe(1)
    locals = frame.f_locals

    # Try to make sure we were called from a class def.
    if (locals is frame.f_globals) or ('__module__' not in locals):
        raise TypeError("dependsOn can be used only from a class definition.")
    ref = reference(reftype=itemType, doc=doc, indexed=indexed, allowNone=True,
                    whenDeleted=whenDeleted)
    if "__dependsOn_advice_data__" not in locals:
        addClassAdvisor(_dependsOn_advice)
    locals.setdefault('__dependsOn_advice_data__', []).append(
    (itemType, itemCustomizer, ref))
    return ref
Esempio n. 28
0
def layout(engine, *args, **kwargs):
    """
    This will attach a layout to the view allowing for auto loading of
    widgets.
    
    This should be used from within a class such as:
    
    >>> class MyView(View):
    ...     layout('glade', filename = 'myview.glade')
    ...
    >>>
    
    @engine: the layout engine to use such as 'glade'
    """
    if engine not in _layout_engines:
        raise AttributeError, 'Engine %s could not be found' % engine
    
    action = (_layout_engines[engine], args, kwargs)
    def installAction(cls):
        if not hasattr(cls, '_lift_items'):
            cls._lift_items = []
        cls._lift_items.append(action)
        return cls
    addClassAdvisor(installAction)
Esempio n. 29
0
def secured_by(*securityinfos):
    """
        Declare that object(s) 'securityinfos' provide
        security information for klass being defind during call.
    """
    for securityinfo in securityinfos:
        if not ISecurityInformation.providedBy(securityinfo):
            raise TypeError('Security objects must provide ISecurityInfo.')

    ##
    # Closure formed by inner-function allows delayed assignement
    #   of security information.
    def setup_security_info(klass):
        if not vars(klass).has_key('__secured_by__'):
            klass.__secured_by__ = []
        map(klass.__secured_by__.append, securityinfos)
        return klass
    return _zadvice.addClassAdvisor(setup_security_info)
Esempio n. 30
0
def secured_by(*securityinfos):
    """
        Declare that object(s) 'securityinfos' provide
        security information for klass being defind during call.
    """
    for securityinfo in securityinfos:
        if not ISecurityInformation.providedBy(securityinfo):
            raise TypeError('Security objects must provide ISecurityInfo.')

    ##
    # Closure formed by inner-function allows delayed assignement
    #   of security information.
    def setup_security_info(klass):
        if not vars(klass).has_key('__secured_by__'):
            klass.__secured_by__ = []
        map(klass.__secured_by__.append, securityinfos)
        return klass

    return _zadvice.addClassAdvisor(setup_security_info)
Esempio n. 31
0
def adapts(*interfaces):
    """
        Called within adapter class definitions.  Parameter 'interface'
        may be single Interface type object, or list of interfaces if
        adapter is to be a multi-adapter.  A multi-adapter adapts
        multiple objects, by interface, to some interface.

        Note: inner-function uses closure to bind 'interface', which
        is provided now, and klass which will be provided to inner function
        when called upon completion of current class statement.

        Inner-function must return klass reference as it is being called
        in similar-fashion as meta-class.
    """
    def setup_adapts(klass):
        if not vars(klass).has_key('__used_for__'):
            klass.__used_for__ = []
        map(klass.__used_for__.append, interfaces)
        return klass
    return _zadvice.addClassAdvisor(setup_adapts)
Esempio n. 32
0
def adapts(*interfaces):
    """
        Called within adapter class definitions.  Parameter 'interface'
        may be single Interface type object, or list of interfaces if
        adapter is to be a multi-adapter.  A multi-adapter adapts
        multiple objects, by interface, to some interface.

        Note: inner-function uses closure to bind 'interface', which
        is provided now, and klass which will be provided to inner function
        when called upon completion of current class statement.

        Inner-function must return klass reference as it is being called
        in similar-fashion as meta-class.
    """
    def setup_adapts(klass):
        if not vars(klass).has_key('__used_for__'):
            klass.__used_for__ = []
        map(klass.__used_for__.append, interfaces)
        return klass

    return _zadvice.addClassAdvisor(setup_adapts)
Esempio n. 33
0
def logger(category):
    def setCategory(cls):
        cls._logger_category = category
        return cls
    addClassAdvisor(setCategory)
Esempio n. 34
0
 def __call__(self, fn):
     self.fn = fn
     addClassAdvisor(self.advise)
     return fn
Esempio n. 35
0
def classProvides(*interfaces):
    """Declare interfaces provided directly by a class

      This function is called in a class definition.

      The arguments are one or more interfaces or interface
      specifications (IDeclaration objects).

      The given interfaces (including the interfaces in the
      specifications) are used to create the class's direct-object
      interface specification.  An error will be raised if the module
      class has an direct interface specification.  In other words, it is
      an error to call this function more than once in a class
      definition.

      Note that the given interfaces have nothing to do with the
      interfaces implemented by instances of the class.

      This function is provided for convenience. It provides a more
      convenient way to call directlyProvidedByProvides for a class. For
      example::

        classProvides(I1)

      is equivalent to calling::

        directlyProvides(theclass, I1)

      after the class has been created.

      For example::

            >>> from zope.interface import Interface
            >>> class IFoo(Interface): pass
            ...
            >>> class IFooFactory(Interface): pass
            ...
            >>> class C(object):
            ...   implements(IFoo)
            ...   classProvides(IFooFactory)
            >>> [i.getName() for i in C.__providedBy__]
            ['IFooFactory']
            >>> [i.getName() for i in C().__providedBy__]
            ['IFoo']

      if equivalent to::

            >>> from zope.interface import Interface
            >>> class IFoo(Interface): pass
            ...
            >>> class IFooFactory(Interface): pass
            ...
            >>> class C(object):
            ...   implements(IFoo)
            >>> directlyProvides(C, IFooFactory)
            >>> [i.getName() for i in C.__providedBy__]
            ['IFooFactory']
            >>> [i.getName() for i in C().__providedBy__]
            ['IFoo']


      """
    frame = sys._getframe(1)
    locals = frame.f_locals

    # Try to make sure we were called from a class def
    if (locals is frame.f_globals) or ('__module__' not in locals):
        raise TypeError(name+" can be used only from a class definition.")

    if '__provides__' in locals:
        raise TypeError(
            "classProvides can only be used once in a class definition.")

    locals["__provides__"] = _normalizeargs(interfaces)

    addClassAdvisor(_classProvides_advice, depth=2)
Esempio n. 36
0
def ping(log, value):
    def pong(klass):
        log.append((value, klass))
        return [klass]

    addClassAdvisor(pong)
Esempio n. 37
0
 def factory(self, *schemas):
     addClassAdvisor(_schema_advice, depth=3)
     return list(schemas)
Esempio n. 38
0
    def factory(*types):
        """
        The eventtype-specific decorator factory. Calling this factory both
        produces a decorator and wraps the __init__ of the class of the
        decorated method with a function that registers the handlers.
        """
        # Create a mutable to store the handler name between the call to
        # decorator and the call to advisor (simple assignment won't work for
        # scope reasons)
        _f = {}

        def decorator(f):
            """
            The decorator. All it does is print a log message, then call the
            original function.
            """
            def inner(self, obj, event):
                # Log that we've called this listener
                fname = '.'.join((self.__class__.__name__, f.__name__))
                log.debug('%s is interested in %r for %r' % (fname, event, obj))

                # Call the original function
                return f(self, obj, event)

            # Push the name of the function outside the decorator scope so the
            # class advisor has access when it needs to register handlers.
            _f[f.__name__] = 1

            # Return the closure to replace the original function.
            return inner

        def advisor(cls):
            """
            A class advisor that is called after the class is created. We use
            this to wrap __init__ in a function that registers any handlers
            created via this factory, which are stored on the class.
            """
            # Set one flag per fname on the class so we don't double-register
            # when we override in a subclass (once for super, once for sub)
            fname = _f.keys()[0]
            cls.__registered = getattr(cls, '__registered', {})

            # Check our flag
            if fname not in cls.__registered or not issubclass(cls, tuple(cls.__registered[fname])):
                # Decorator for __init__
                def registerHandlers(f):
                    def __init__(self, *args, **kwargs):
                        # Call the original constructor; we'll register handlers
                        # afterwards
                        f(self, *args, **kwargs)
                        handler = getattr(self, fname)
                        for t in types:
                            # Register the handler. Here's where we use
                            # eventtype, which was passed in to the outermost
                            # function in this behemoth.
                            provideHandler(handler, (t, eventtype))

                    # Return the closure to replace the decorated method
                    return __init__

                # Decorate __init__ so it will register the handlers on
                # instantiation
                cls.__init__ = registerHandlers(cls.__init__)
                # Set the flag for this fname
                cls.__registered.setdefault(fname, []).append(cls)


            # Return the class, which will replace the original class.
            return cls

        # Add the advisor to the class.
        addClassAdvisor(advisor)

        # Return the decorator so we get the log message when called
        return decorator
Esempio n. 39
0
 def factory(self, *schemas):
     addClassAdvisor(_schema_advice, depth=3)
     return list(schemas)
Esempio n. 40
0
def classProvides(*interfaces):
    """Declare interfaces provided directly by a class

      This function is called in a class definition.

      The arguments are one or more interfaces or interface specifications
      (``IDeclaration`` objects).

      The given interfaces (including the interfaces in the specifications)
      are used to create the class's direct-object interface specification.
      An error will be raised if the module class has an direct interface
      specification. In other words, it is an error to call this function more
      than once in a class definition.

      Note that the given interfaces have nothing to do with the interfaces
      implemented by instances of the class.

      This function is provided for convenience. It provides a more convenient
      way to call directlyProvides for a class. For example::

        classProvides(I1)

      is equivalent to calling::

        directlyProvides(theclass, I1)

      after the class has been created.

      For example:

        >>> from zope.interface import Interface
        >>> class IFoo(Interface): pass
        ...
        >>> class IFooFactory(Interface): pass
        ...
        >>> class C(object):
        ...   implements(IFoo)
        ...   classProvides(IFooFactory)
        >>> [i.getName() for i in C.__providedBy__]
        ['IFooFactory']
        >>> [i.getName() for i in C().__providedBy__]
        ['IFoo']

      if equivalent to:

        >>> from zope.interface import Interface
        >>> class IFoo(Interface): pass
        ...
        >>> class IFooFactory(Interface): pass
        ...
        >>> class C(object):
        ...   implements(IFoo)
        >>> directlyProvides(C, IFooFactory)
        >>> [i.getName() for i in C.__providedBy__]
        ['IFooFactory']
        >>> [i.getName() for i in C().__providedBy__]
        ['IFoo']

      If classProvides is called outside of a class definition, it fails.

        >>> classProvides(IFooFactory)
        Traceback (most recent call last):
        ...
        TypeError: classProvides can be used only from a class definition.

      """
    frame = sys._getframe(1)
    locals = frame.f_locals

    # Try to make sure we were called from a class def
    if (locals is frame.f_globals) or ('__module__' not in locals):
        raise TypeError(
            "classProvides can be used only from a class definition.")

    if '__provides__' in locals:
        raise TypeError(
            "classProvides can only be used once in a class definition.")

    locals["__provides__"] = _normalizeargs(interfaces)

    addClassAdvisor(_classProvides_advice, depth=2)
Esempio n. 41
0
    def factory(*types):
        """
        The eventtype-specific decorator factory. Calling this factory both
        produces a decorator and wraps the __init__ of the class of the
        decorated method with a function that registers the handlers.
        """
        # Create a mutable to store the handler name between the call to
        # decorator and the call to advisor (simple assignment won't work for
        # scope reasons)
        _f = {}

        def decorator(f):
            """
            The decorator. All it does is print a log message, then call the
            original function.
            """
            def inner(self, obj, event):
                # Log that we've called this listener
                fname = '.'.join((self.__class__.__name__, f.__name__))
                log.debug('%s is interested in %r for %r' %
                          (fname, event, obj))

                # Call the original function
                return f(self, obj, event)

            # Push the name of the function outside the decorator scope so the
            # class advisor has access when it needs to register handlers.
            _f[f.__name__] = 1

            # Return the closure to replace the original function.
            return inner

        def advisor(cls):
            """
            A class advisor that is called after the class is created. We use
            this to wrap __init__ in a function that registers any handlers
            created via this factory, which are stored on the class.
            """
            # Set one flag per fname on the class so we don't double-register
            # when we override in a subclass (once for super, once for sub)
            fname = _f.keys()[0]
            cls.__registered = getattr(cls, '__registered', {})

            # Check our flag
            if fname not in cls.__registered or not issubclass(
                    cls, tuple(cls.__registered[fname])):
                # Decorator for __init__
                def registerHandlers(f):
                    def __init__(self, *args, **kwargs):
                        # Call the original constructor; we'll register handlers
                        # afterwards
                        f(self, *args, **kwargs)
                        handler = getattr(self, fname)
                        for t in types:
                            # Register the handler. Here's where we use
                            # eventtype, which was passed in to the outermost
                            # function in this behemoth.
                            provideHandler(handler, (t, eventtype))

                    # Return the closure to replace the decorated method
                    return __init__

                # Decorate __init__ so it will register the handlers on
                # instantiation
                cls.__init__ = registerHandlers(cls.__init__)
                # Set the flag for this fname
                cls.__registered.setdefault(fname, []).append(cls)

            # Return the class, which will replace the original class.
            return cls

        # Add the advisor to the class.
        addClassAdvisor(advisor)

        # Return the decorator so we get the log message when called
        return decorator
        if interesting_modules.match(cls.__module__):
            if not excluded_classnames.match(cls.__name__):
                for interface in interfaces:
                    try:
                        verifyClass(interface, cls)
                    except Exception, e:
                        print >>_err, ("%s.%s does not correctly implement %s.%s:\n%s"
                                       % (cls.__module__, cls.__name__,
                                          interface.__module__, interface.__name__, e))
        else:
            _other_modules_with_violations.add(cls.__module__)
        return cls

    f_locals['__implements_advice_data__'] = interfaces, zi.classImplements
    addClassAdvisor(_implements_advice, depth=2)


def check():
    # patchee-monkey
    zi.implements = strictly_implements

    if len(sys.argv) >= 2:
        if sys.argv[1] == '--help' or len(sys.argv) > 2:
            print >>_err, "Usage: check-miscaptures.py [SOURCEDIR]"
            return
        srcdir = sys.argv[1]
    else:
        # import modules under src/ by default
        srcdir = 'src'