Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/zope/interface/interfaces.py : 99%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1##############################################################################
2#
3# Copyright (c) 2002 Zope Foundation and Contributors.
4# All Rights Reserved.
5#
6# This software is subject to the provisions of the Zope Public License,
7# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
8# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
9# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
10# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
11# FOR A PARTICULAR PURPOSE.
12#
13##############################################################################
14"""Interface Package Interfaces
15"""
16__docformat__ = 'restructuredtext'
18from zope.interface.interface import Attribute
19from zope.interface.interface import Interface
20from zope.interface.declarations import implementer
22__all__ = [
23 'IAdapterRegistration',
24 'IAdapterRegistry',
25 'IAttribute',
26 'IComponentLookup',
27 'IComponentRegistry',
28 'IComponents',
29 'IDeclaration',
30 'IElement',
31 'IHandlerRegistration',
32 'IInterface',
33 'IInterfaceDeclaration',
34 'IMethod',
35 'IObjectEvent',
36 'IRegistered',
37 'IRegistration',
38 'IRegistrationEvent',
39 'ISpecification',
40 'ISubscriptionAdapterRegistration',
41 'IUnregistered',
42 'IUtilityRegistration',
43]
45# pylint:disable=inherit-non-class,no-method-argument,no-self-argument
46# pylint:disable=unexpected-special-method-signature
47# pylint:disable=too-many-lines
49class IElement(Interface):
50 """
51 Objects that have basic documentation and tagged values.
53 Known derivatives include :class:`IAttribute` and its derivative
54 :class:`IMethod`; these have no notion of inheritance.
55 :class:`IInterface` is also a derivative, and it does have a
56 notion of inheritance, expressed through its ``__bases__`` and
57 ordered in its ``__iro__`` (both defined by
58 :class:`ISpecification`).
59 """
61 # pylint:disable=arguments-differ
63 # Note that defining __doc__ as an Attribute hides the docstring
64 # from introspection. When changing it, also change it in the Sphinx
65 # ReST files.
67 __name__ = Attribute('__name__', 'The object name')
68 __doc__ = Attribute('__doc__', 'The object doc string')
70 ###
71 # Tagged values.
72 #
73 # Direct values are established in this instance. Others may be
74 # inherited. Although ``IElement`` itself doesn't have a notion of
75 # inheritance, ``IInterface`` *does*. It might have been better to
76 # make ``IInterface`` define new methods
77 # ``getIndirectTaggedValue``, etc, to include inheritance instead
78 # of overriding ``getTaggedValue`` to do that, but that ship has sailed.
79 # So to keep things nice and symmetric, we define the ``Direct`` methods here.
80 ###
82 def getTaggedValue(tag):
83 """Returns the value associated with *tag*.
85 Raise a `KeyError` if the tag isn't set.
87 If the object has a notion of inheritance, this searches
88 through the inheritance hierarchy and returns the nearest result.
89 If there is no such notion, this looks only at this object.
91 .. versionchanged:: 4.7.0
92 This method should respect inheritance if present.
93 """
95 def queryTaggedValue(tag, default=None):
96 """
97 As for `getTaggedValue`, but instead of raising a `KeyError`, returns *default*.
100 .. versionchanged:: 4.7.0
101 This method should respect inheritance if present.
102 """
104 def getTaggedValueTags():
105 """
106 Returns a collection of all tags in no particular order.
108 If the object has a notion of inheritance, this
109 includes all the inherited tagged values. If there is
110 no such notion, this looks only at this object.
112 .. versionchanged:: 4.7.0
113 This method should respect inheritance if present.
114 """
116 def setTaggedValue(tag, value):
117 """
118 Associates *value* with *key* directly in this object.
119 """
121 def getDirectTaggedValue(tag):
122 """
123 As for `getTaggedValue`, but never includes inheritance.
125 .. versionadded:: 5.0.0
126 """
128 def queryDirectTaggedValue(tag, default=None):
129 """
130 As for `queryTaggedValue`, but never includes inheritance.
132 .. versionadded:: 5.0.0
133 """
135 def getDirectTaggedValueTags():
136 """
137 As for `getTaggedValueTags`, but includes only tags directly
138 set on this object.
140 .. versionadded:: 5.0.0
141 """
144class IAttribute(IElement):
145 """Attribute descriptors"""
147 interface = Attribute('interface',
148 'Stores the interface instance in which the '
149 'attribute is located.')
152class IMethod(IAttribute):
153 """Method attributes"""
155 def getSignatureInfo():
156 """Returns the signature information.
158 This method returns a dictionary with the following string keys:
160 - positional
161 A sequence of the names of positional arguments.
162 - required
163 A sequence of the names of required arguments.
164 - optional
165 A dictionary mapping argument names to their default values.
166 - varargs
167 The name of the varargs argument (or None).
168 - kwargs
169 The name of the kwargs argument (or None).
170 """
172 def getSignatureString():
173 """Return a signature string suitable for inclusion in documentation.
175 This method returns the function signature string. For example, if you
176 have ``def func(a, b, c=1, d='f')``, then the signature string is ``"(a, b,
177 c=1, d='f')"``.
178 """
180class ISpecification(Interface):
181 """Object Behavioral specifications"""
182 # pylint:disable=arguments-differ
183 def providedBy(object): # pylint:disable=redefined-builtin
184 """Test whether the interface is implemented by the object
186 Return true of the object asserts that it implements the
187 interface, including asserting that it implements an extended
188 interface.
189 """
191 def implementedBy(class_):
192 """Test whether the interface is implemented by instances of the class
194 Return true of the class asserts that its instances implement the
195 interface, including asserting that they implement an extended
196 interface.
197 """
199 def isOrExtends(other):
200 """Test whether the specification is or extends another
201 """
203 def extends(other, strict=True):
204 """Test whether a specification extends another
206 The specification extends other if it has other as a base
207 interface or if one of it's bases extends other.
209 If strict is false, then the specification extends itself.
210 """
212 def weakref(callback=None):
213 """Return a weakref to the specification
215 This method is, regrettably, needed to allow weakrefs to be
216 computed to security-proxied specifications. While the
217 zope.interface package does not require zope.security or
218 zope.proxy, it has to be able to coexist with it.
220 """
222 __bases__ = Attribute("""Base specifications
224 A tuple of specifications from which this specification is
225 directly derived.
227 """)
229 __sro__ = Attribute("""Specification-resolution order
231 A tuple of the specification and all of it's ancestor
232 specifications from most specific to least specific. The specification
233 itself is the first element.
235 (This is similar to the method-resolution order for new-style classes.)
236 """)
238 __iro__ = Attribute("""Interface-resolution order
240 A tuple of the specification's ancestor interfaces from
241 most specific to least specific. The specification itself is
242 included if it is an interface.
244 (This is similar to the method-resolution order for new-style classes.)
245 """)
247 def get(name, default=None):
248 """Look up the description for a name
250 If the named attribute is not defined, the default is
251 returned.
252 """
255class IInterface(ISpecification, IElement):
256 """Interface objects
258 Interface objects describe the behavior of an object by containing
259 useful information about the object. This information includes:
261 - Prose documentation about the object. In Python terms, this
262 is called the "doc string" of the interface. In this element,
263 you describe how the object works in prose language and any
264 other useful information about the object.
266 - Descriptions of attributes. Attribute descriptions include
267 the name of the attribute and prose documentation describing
268 the attributes usage.
270 - Descriptions of methods. Method descriptions can include:
272 - Prose "doc string" documentation about the method and its
273 usage.
275 - A description of the methods arguments; how many arguments
276 are expected, optional arguments and their default values,
277 the position or arguments in the signature, whether the
278 method accepts arbitrary arguments and whether the method
279 accepts arbitrary keyword arguments.
281 - Optional tagged data. Interface objects (and their attributes and
282 methods) can have optional, application specific tagged data
283 associated with them. Examples uses for this are examples,
284 security assertions, pre/post conditions, and other possible
285 information you may want to associate with an Interface or its
286 attributes.
288 Not all of this information is mandatory. For example, you may
289 only want the methods of your interface to have prose
290 documentation and not describe the arguments of the method in
291 exact detail. Interface objects are flexible and let you give or
292 take any of these components.
294 Interfaces are created with the Python class statement using
295 either `zope.interface.Interface` or another interface, as in::
297 from zope.interface import Interface
299 class IMyInterface(Interface):
300 '''Interface documentation'''
302 def meth(arg1, arg2):
303 '''Documentation for meth'''
305 # Note that there is no self argument
307 class IMySubInterface(IMyInterface):
308 '''Interface documentation'''
310 def meth2():
311 '''Documentation for meth2'''
313 You use interfaces in two ways:
315 - You assert that your object implement the interfaces.
317 There are several ways that you can declare that an object
318 provides an interface:
320 1. Call `zope.interface.implementer` on your class definition.
322 2. Call `zope.interface.directlyProvides` on your object.
324 3. Call `zope.interface.classImplements` to declare that instances
325 of a class implement an interface.
327 For example::
329 from zope.interface import classImplements
331 classImplements(some_class, some_interface)
333 This approach is useful when it is not an option to modify
334 the class source. Note that this doesn't affect what the
335 class itself implements, but only what its instances
336 implement.
338 - You query interface meta-data. See the IInterface methods and
339 attributes for details.
341 """
342 # pylint:disable=arguments-differ
343 def names(all=False): # pylint:disable=redefined-builtin
344 """Get the interface attribute names
346 Return a collection of the names of the attributes, including
347 methods, included in the interface definition.
349 Normally, only directly defined attributes are included. If
350 a true positional or keyword argument is given, then
351 attributes defined by base classes will be included.
352 """
354 def namesAndDescriptions(all=False): # pylint:disable=redefined-builtin
355 """Get the interface attribute names and descriptions
357 Return a collection of the names and descriptions of the
358 attributes, including methods, as name-value pairs, included
359 in the interface definition.
361 Normally, only directly defined attributes are included. If
362 a true positional or keyword argument is given, then
363 attributes defined by base classes will be included.
364 """
366 def __getitem__(name):
367 """Get the description for a name
369 If the named attribute is not defined, a `KeyError` is raised.
370 """
372 def direct(name):
373 """Get the description for the name if it was defined by the interface
375 If the interface doesn't define the name, returns None.
376 """
378 def validateInvariants(obj, errors=None):
379 """Validate invariants
381 Validate object to defined invariants. If errors is None,
382 raises first Invalid error; if errors is a list, appends all errors
383 to list, then raises Invalid with the errors as the first element
384 of the "args" tuple."""
386 def __contains__(name):
387 """Test whether the name is defined by the interface"""
389 def __iter__():
390 """Return an iterator over the names defined by the interface
392 The names iterated include all of the names defined by the
393 interface directly and indirectly by base interfaces.
394 """
396 __module__ = Attribute("""The name of the module defining the interface""")
399class IDeclaration(ISpecification):
400 """Interface declaration
402 Declarations are used to express the interfaces implemented by
403 classes or provided by objects.
404 """
406 def __contains__(interface):
407 """Test whether an interface is in the specification
409 Return true if the given interface is one of the interfaces in
410 the specification and false otherwise.
411 """
413 def __iter__():
414 """Return an iterator for the interfaces in the specification
415 """
417 def flattened():
418 """Return an iterator of all included and extended interfaces
420 An iterator is returned for all interfaces either included in
421 or extended by interfaces included in the specifications
422 without duplicates. The interfaces are in "interface
423 resolution order". The interface resolution order is such that
424 base interfaces are listed after interfaces that extend them
425 and, otherwise, interfaces are included in the order that they
426 were defined in the specification.
427 """
429 def __sub__(interfaces):
430 """Create an interface specification with some interfaces excluded
432 The argument can be an interface or an interface
433 specifications. The interface or interfaces given in a
434 specification are subtracted from the interface specification.
436 Removing an interface that is not in the specification does
437 not raise an error. Doing so has no effect.
439 Removing an interface also removes sub-interfaces of the interface.
441 """
443 def __add__(interfaces):
444 """Create an interface specification with some interfaces added
446 The argument can be an interface or an interface
447 specifications. The interface or interfaces given in a
448 specification are added to the interface specification.
450 Adding an interface that is already in the specification does
451 not raise an error. Doing so has no effect.
452 """
454 def __nonzero__():
455 """Return a true value of the interface specification is non-empty
456 """
458class IInterfaceDeclaration(Interface):
459 """
460 Declare and check the interfaces of objects.
462 The functions defined in this interface are used to declare the
463 interfaces that objects provide and to query the interfaces that
464 have been declared.
466 Interfaces can be declared for objects in two ways:
468 - Interfaces are declared for instances of the object's class
470 - Interfaces are declared for the object directly.
472 The interfaces declared for an object are, therefore, the union of
473 interfaces declared for the object directly and the interfaces
474 declared for instances of the object's class.
476 Note that we say that a class implements the interfaces provided
477 by it's instances. An instance can also provide interfaces
478 directly. The interfaces provided by an object are the union of
479 the interfaces provided directly and the interfaces implemented by
480 the class.
482 This interface is implemented by :mod:`zope.interface`.
483 """
484 # pylint:disable=arguments-differ
485 ###
486 # Defining interfaces
487 ###
489 Interface = Attribute("The base class used to create new interfaces")
491 def taggedValue(key, value):
492 """
493 Attach a tagged value to an interface while defining the interface.
495 This is a way of executing :meth:`IElement.setTaggedValue` from
496 the definition of the interface. For example::
498 class IFoo(Interface):
499 taggedValue('key', 'value')
501 .. seealso:: `zope.interface.taggedValue`
502 """
504 def invariant(checker_function):
505 """
506 Attach an invariant checker function to an interface while defining it.
508 Invariants can later be validated against particular implementations by
509 calling :meth:`IInterface.validateInvariants`.
511 For example::
513 def check_range(ob):
514 if ob.max < ob.min:
515 raise ValueError("max value is less than min value")
517 class IRange(Interface):
518 min = Attribute("The min value")
519 max = Attribute("The max value")
521 invariant(check_range)
523 .. seealso:: `zope.interface.invariant`
524 """
526 def interfacemethod(method):
527 """
528 A decorator that transforms a method specification into an
529 implementation method.
531 This is used to override methods of ``Interface`` or provide new methods.
532 Definitions using this decorator will not appear in :meth:`IInterface.names()`.
533 It is possible to have an implementation method and a method specification
534 of the same name.
536 For example::
538 class IRange(Interface):
539 @interfacemethod
540 def __adapt__(self, obj):
541 if isinstance(obj, range):
542 # Return the builtin ``range`` as-is
543 return obj
544 return super(type(IRange), self).__adapt__(obj)
546 You can use ``super`` to call the parent class functionality. Note that
547 the zero-argument version (``super().__adapt__``) works on Python 3.6 and above, but
548 prior to that the two-argument version must be used, and the class must be explicitly
549 passed as the first argument.
551 .. versionadded:: 5.1.0
552 .. seealso:: `zope.interface.interfacemethod`
553 """
555 ###
556 # Querying interfaces
557 ###
559 def providedBy(ob):
560 """
561 Return the interfaces provided by an object.
563 This is the union of the interfaces directly provided by an
564 object and interfaces implemented by it's class.
566 The value returned is an `IDeclaration`.
568 .. seealso:: `zope.interface.providedBy`
569 """
571 def implementedBy(class_):
572 """
573 Return the interfaces implemented for a class's instances.
575 The value returned is an `IDeclaration`.
577 .. seealso:: `zope.interface.implementedBy`
578 """
580 ###
581 # Declaring interfaces
582 ###
584 def classImplements(class_, *interfaces):
585 """
586 Declare additional interfaces implemented for instances of a class.
588 The arguments after the class are one or more interfaces or
589 interface specifications (`IDeclaration` objects).
591 The interfaces given (including the interfaces in the
592 specifications) are added to any interfaces previously
593 declared.
595 Consider the following example::
597 class C(A, B):
598 ...
600 classImplements(C, I1, I2)
603 Instances of ``C`` provide ``I1``, ``I2``, and whatever interfaces
604 instances of ``A`` and ``B`` provide. This is equivalent to::
606 @implementer(I1, I2)
607 class C(A, B):
608 pass
610 .. seealso:: `zope.interface.classImplements`
611 .. seealso:: `zope.interface.implementer`
612 """
614 def classImplementsFirst(cls, interface):
615 """
616 See :func:`zope.interface.classImplementsFirst`.
617 """
619 def implementer(*interfaces):
620 """
621 Create a decorator for declaring interfaces implemented by a
622 factory.
624 A callable is returned that makes an implements declaration on
625 objects passed to it.
627 .. seealso:: :meth:`classImplements`
628 """
630 def classImplementsOnly(class_, *interfaces):
631 """
632 Declare the only interfaces implemented by instances of a class.
634 The arguments after the class are one or more interfaces or
635 interface specifications (`IDeclaration` objects).
637 The interfaces given (including the interfaces in the
638 specifications) replace any previous declarations.
640 Consider the following example::
642 class C(A, B):
643 ...
645 classImplements(C, IA, IB. IC)
646 classImplementsOnly(C. I1, I2)
648 Instances of ``C`` provide only ``I1``, ``I2``, and regardless of
649 whatever interfaces instances of ``A`` and ``B`` implement.
651 .. seealso:: `zope.interface.classImplementsOnly`
652 """
654 def implementer_only(*interfaces):
655 """
656 Create a decorator for declaring the only interfaces implemented.
658 A callable is returned that makes an implements declaration on
659 objects passed to it.
661 .. seealso:: `zope.interface.implementer_only`
662 """
664 def directlyProvidedBy(object): # pylint:disable=redefined-builtin
665 """
666 Return the interfaces directly provided by the given object.
668 The value returned is an `IDeclaration`.
670 .. seealso:: `zope.interface.directlyProvidedBy`
671 """
673 def directlyProvides(object, *interfaces): # pylint:disable=redefined-builtin
674 """
675 Declare interfaces declared directly for an object.
677 The arguments after the object are one or more interfaces or
678 interface specifications (`IDeclaration` objects).
680 .. caution::
681 The interfaces given (including the interfaces in the
682 specifications) *replace* interfaces previously
683 declared for the object. See :meth:`alsoProvides` to add
684 additional interfaces.
686 Consider the following example::
688 class C(A, B):
689 ...
691 ob = C()
692 directlyProvides(ob, I1, I2)
694 The object, ``ob`` provides ``I1``, ``I2``, and whatever interfaces
695 instances have been declared for instances of ``C``.
697 To remove directly provided interfaces, use `directlyProvidedBy` and
698 subtract the unwanted interfaces. For example::
700 directlyProvides(ob, directlyProvidedBy(ob)-I2)
702 removes I2 from the interfaces directly provided by
703 ``ob``. The object, ``ob`` no longer directly provides ``I2``,
704 although it might still provide ``I2`` if it's class
705 implements ``I2``.
707 To add directly provided interfaces, use `directlyProvidedBy` and
708 include additional interfaces. For example::
710 directlyProvides(ob, directlyProvidedBy(ob), I2)
712 adds I2 to the interfaces directly provided by ob.
714 .. seealso:: `zope.interface.directlyProvides`
715 """
717 def alsoProvides(object, *interfaces): # pylint:disable=redefined-builtin
718 """
719 Declare additional interfaces directly for an object.
721 For example::
723 alsoProvides(ob, I1)
725 is equivalent to::
727 directlyProvides(ob, directlyProvidedBy(ob), I1)
729 .. seealso:: `zope.interface.alsoProvides`
730 """
732 def noLongerProvides(object, interface): # pylint:disable=redefined-builtin
733 """
734 Remove an interface from the list of an object's directly provided
735 interfaces.
737 For example::
739 noLongerProvides(ob, I1)
741 is equivalent to::
743 directlyProvides(ob, directlyProvidedBy(ob) - I1)
745 with the exception that if ``I1`` is an interface that is
746 provided by ``ob`` through the class's implementation,
747 `ValueError` is raised.
749 .. seealso:: `zope.interface.noLongerProvides`
750 """
752 def implements(*interfaces):
753 """
754 Declare interfaces implemented by instances of a class.
756 .. deprecated:: 5.0
757 This only works for Python 2. The `implementer` decorator
758 is preferred for all versions.
760 This function is called in a class definition (Python 2.x only).
762 The arguments are one or more interfaces or interface
763 specifications (`IDeclaration` objects).
765 The interfaces given (including the interfaces in the
766 specifications) are added to any interfaces previously
767 declared.
769 Previous declarations include declarations for base classes
770 unless implementsOnly was used.
772 This function is provided for convenience. It provides a more
773 convenient way to call `classImplements`. For example::
775 implements(I1)
777 is equivalent to calling::
779 classImplements(C, I1)
781 after the class has been created.
783 Consider the following example (Python 2.x only)::
785 class C(A, B):
786 implements(I1, I2)
789 Instances of ``C`` implement ``I1``, ``I2``, and whatever interfaces
790 instances of ``A`` and ``B`` implement.
791 """
793 def implementsOnly(*interfaces):
794 """
795 Declare the only interfaces implemented by instances of a class.
797 .. deprecated:: 5.0
798 This only works for Python 2. The `implementer_only` decorator
799 is preferred for all versions.
801 This function is called in a class definition (Python 2.x only).
803 The arguments are one or more interfaces or interface
804 specifications (`IDeclaration` objects).
806 Previous declarations including declarations for base classes
807 are overridden.
809 This function is provided for convenience. It provides a more
810 convenient way to call `classImplementsOnly`. For example::
812 implementsOnly(I1)
814 is equivalent to calling::
816 classImplementsOnly(I1)
818 after the class has been created.
820 Consider the following example (Python 2.x only)::
822 class C(A, B):
823 implementsOnly(I1, I2)
826 Instances of ``C`` implement ``I1``, ``I2``, regardless of what
827 instances of ``A`` and ``B`` implement.
828 """
830 def classProvides(*interfaces):
831 """
832 Declare interfaces provided directly by a class.
834 .. deprecated:: 5.0
835 This only works for Python 2. The `provider` decorator
836 is preferred for all versions.
838 This function is called in a class definition.
840 The arguments are one or more interfaces or interface
841 specifications (`IDeclaration` objects).
843 The given interfaces (including the interfaces in the
844 specifications) are used to create the class's direct-object
845 interface specification. An error will be raised if the module
846 class has an direct interface specification. In other words, it is
847 an error to call this function more than once in a class
848 definition.
850 Note that the given interfaces have nothing to do with the
851 interfaces implemented by instances of the class.
853 This function is provided for convenience. It provides a more
854 convenient way to call `directlyProvides` for a class. For example::
856 classProvides(I1)
858 is equivalent to calling::
860 directlyProvides(theclass, I1)
862 after the class has been created.
863 """
865 def provider(*interfaces):
866 """
867 A class decorator version of `classProvides`.
869 .. seealso:: `zope.interface.provider`
870 """
872 def moduleProvides(*interfaces):
873 """
874 Declare interfaces provided by a module.
876 This function is used in a module definition.
878 The arguments are one or more interfaces or interface
879 specifications (`IDeclaration` objects).
881 The given interfaces (including the interfaces in the
882 specifications) are used to create the module's direct-object
883 interface specification. An error will be raised if the module
884 already has an interface specification. In other words, it is
885 an error to call this function more than once in a module
886 definition.
888 This function is provided for convenience. It provides a more
889 convenient way to call `directlyProvides` for a module. For example::
891 moduleImplements(I1)
893 is equivalent to::
895 directlyProvides(sys.modules[__name__], I1)
897 .. seealso:: `zope.interface.moduleProvides`
898 """
900 def Declaration(*interfaces):
901 """
902 Create an interface specification.
904 The arguments are one or more interfaces or interface
905 specifications (`IDeclaration` objects).
907 A new interface specification (`IDeclaration`) with the given
908 interfaces is returned.
910 .. seealso:: `zope.interface.Declaration`
911 """
913class IAdapterRegistry(Interface):
914 """Provide an interface-based registry for adapters
916 This registry registers objects that are in some sense "from" a
917 sequence of specification to an interface and a name.
919 No specific semantics are assumed for the registered objects,
920 however, the most common application will be to register factories
921 that adapt objects providing required specifications to a provided
922 interface.
923 """
925 def register(required, provided, name, value):
926 """Register a value
928 A value is registered for a *sequence* of required specifications, a
929 provided interface, and a name, which must be text.
930 """
932 def registered(required, provided, name=u''):
933 """Return the component registered for the given interfaces and name
935 name must be text.
937 Unlike the lookup method, this methods won't retrieve
938 components registered for more specific required interfaces or
939 less specific provided interfaces.
941 If no component was registered exactly for the given
942 interfaces and name, then None is returned.
944 """
946 def lookup(required, provided, name='', default=None):
947 """Lookup a value
949 A value is looked up based on a *sequence* of required
950 specifications, a provided interface, and a name, which must be
951 text.
952 """
954 def queryMultiAdapter(objects, provided, name=u'', default=None):
955 """Adapt a sequence of objects to a named, provided, interface
956 """
958 def lookup1(required, provided, name=u'', default=None):
959 """Lookup a value using a single required interface
961 A value is looked up based on a single required
962 specifications, a provided interface, and a name, which must be
963 text.
964 """
966 def queryAdapter(object, provided, name=u'', default=None): # pylint:disable=redefined-builtin
967 """Adapt an object using a registered adapter factory.
968 """
970 def adapter_hook(provided, object, name=u'', default=None): # pylint:disable=redefined-builtin
971 """Adapt an object using a registered adapter factory.
973 name must be text.
974 """
976 def lookupAll(required, provided):
977 """Find all adapters from the required to the provided interfaces
979 An iterable object is returned that provides name-value two-tuples.
980 """
982 def names(required, provided): # pylint:disable=arguments-differ
983 """Return the names for which there are registered objects
984 """
986 def subscribe(required, provided, subscriber): # pylint:disable=arguments-differ
987 """Register a subscriber
989 A subscriber is registered for a *sequence* of required
990 specifications, a provided interface, and a name.
992 Multiple subscribers may be registered for the same (or
993 equivalent) interfaces.
995 .. versionchanged:: 5.1.1
996 Correct the method signature to remove the ``name`` parameter.
997 Subscribers have no names.
998 """
1000 def subscribed(required, provided, subscriber):
1001 """
1002 Check whether the object *subscriber* is registered directly
1003 with this object via a previous call to
1004 ``subscribe(required, provided, subscriber)``.
1006 If the *subscriber*, or one equal to it, has been subscribed,
1007 for the given *required* sequence and *provided* interface,
1008 return that object. (This does not guarantee whether the *subscriber*
1009 itself is returned, or an object equal to it.)
1011 If it has not, return ``None``.
1013 Unlike :meth:`subscriptions`, this method won't retrieve
1014 components registered for more specific required interfaces or
1015 less specific provided interfaces.
1017 .. versionadded:: 5.3.0
1018 """
1020 def subscriptions(required, provided):
1021 """
1022 Get a sequence of subscribers.
1024 Subscribers for a sequence of *required* interfaces, and a *provided*
1025 interface are returned. This takes into account subscribers
1026 registered with this object, as well as those registered with
1027 base adapter registries in the resolution order, and interfaces that
1028 extend *provided*.
1030 .. versionchanged:: 5.1.1
1031 Correct the method signature to remove the ``name`` parameter.
1032 Subscribers have no names.
1033 """
1035 def subscribers(objects, provided):
1036 """
1037 Get a sequence of subscription **adapters**.
1039 This is like :meth:`subscriptions`, but calls the returned
1040 subscribers with *objects* (and optionally returns the results
1041 of those calls), instead of returning the subscribers directly.
1043 :param objects: A sequence of objects; they will be used to
1044 determine the *required* argument to :meth:`subscriptions`.
1045 :param provided: A single interface, or ``None``, to pass
1046 as the *provided* parameter to :meth:`subscriptions`.
1047 If an interface is given, the results of calling each returned
1048 subscriber with the the *objects* are collected and returned
1049 from this method; each result should be an object implementing
1050 the *provided* interface. If ``None``, the resulting subscribers
1051 are still called, but the results are ignored.
1052 :return: A sequence of the results of calling the subscribers
1053 if *provided* is not ``None``. If there are no registered
1054 subscribers, or *provided* is ``None``, this will be an empty
1055 sequence.
1057 .. versionchanged:: 5.1.1
1058 Correct the method signature to remove the ``name`` parameter.
1059 Subscribers have no names.
1060 """
1062# begin formerly in zope.component
1064class ComponentLookupError(LookupError):
1065 """A component could not be found."""
1067class Invalid(Exception):
1068 """A component doesn't satisfy a promise."""
1070class IObjectEvent(Interface):
1071 """An event related to an object.
1073 The object that generated this event is not necessarily the object
1074 refered to by location.
1075 """
1077 object = Attribute("The subject of the event.")
1080@implementer(IObjectEvent)
1081class ObjectEvent(object):
1083 def __init__(self, object): # pylint:disable=redefined-builtin
1084 self.object = object
1087class IComponentLookup(Interface):
1088 """Component Manager for a Site
1090 This object manages the components registered at a particular site. The
1091 definition of a site is intentionally vague.
1092 """
1094 adapters = Attribute(
1095 "Adapter Registry to manage all registered adapters.")
1097 utilities = Attribute(
1098 "Adapter Registry to manage all registered utilities.")
1100 def queryAdapter(object, interface, name=u'', default=None): # pylint:disable=redefined-builtin
1101 """Look for a named adapter to an interface for an object
1103 If a matching adapter cannot be found, returns the default.
1104 """
1106 def getAdapter(object, interface, name=u''): # pylint:disable=redefined-builtin
1107 """Look for a named adapter to an interface for an object
1109 If a matching adapter cannot be found, a `ComponentLookupError`
1110 is raised.
1111 """
1113 def queryMultiAdapter(objects, interface, name=u'', default=None):
1114 """Look for a multi-adapter to an interface for multiple objects
1116 If a matching adapter cannot be found, returns the default.
1117 """
1119 def getMultiAdapter(objects, interface, name=u''):
1120 """Look for a multi-adapter to an interface for multiple objects
1122 If a matching adapter cannot be found, a `ComponentLookupError`
1123 is raised.
1124 """
1126 def getAdapters(objects, provided):
1127 """Look for all matching adapters to a provided interface for objects
1129 Return an iterable of name-adapter pairs for adapters that
1130 provide the given interface.
1131 """
1133 def subscribers(objects, provided):
1134 """Get subscribers
1136 Subscribers are returned that provide the provided interface
1137 and that depend on and are comuted from the sequence of
1138 required objects.
1139 """
1141 def handle(*objects):
1142 """Call handlers for the given objects
1144 Handlers registered for the given objects are called.
1145 """
1147 def queryUtility(interface, name='', default=None):
1148 """Look up a utility that provides an interface.
1150 If one is not found, returns default.
1151 """
1153 def getUtilitiesFor(interface):
1154 """Look up the registered utilities that provide an interface.
1156 Returns an iterable of name-utility pairs.
1157 """
1159 def getAllUtilitiesRegisteredFor(interface):
1160 """Return all registered utilities for an interface
1162 This includes overridden utilities.
1164 An iterable of utility instances is returned. No names are
1165 returned.
1166 """
1168class IRegistration(Interface):
1169 """A registration-information object
1170 """
1172 registry = Attribute("The registry having the registration")
1174 name = Attribute("The registration name")
1176 info = Attribute("""Information about the registration
1178 This is information deemed useful to people browsing the
1179 configuration of a system. It could, for example, include
1180 commentary or information about the source of the configuration.
1181 """)
1183class IUtilityRegistration(IRegistration):
1184 """Information about the registration of a utility
1185 """
1187 factory = Attribute("The factory used to create the utility. Optional.")
1188 component = Attribute("The object registered")
1189 provided = Attribute("The interface provided by the component")
1191class _IBaseAdapterRegistration(IRegistration):
1192 """Information about the registration of an adapter
1193 """
1195 factory = Attribute("The factory used to create adapters")
1197 required = Attribute("""The adapted interfaces
1199 This is a sequence of interfaces adapters by the registered
1200 factory. The factory will be caled with a sequence of objects, as
1201 positional arguments, that provide these interfaces.
1202 """)
1204 provided = Attribute("""The interface provided by the adapters.
1206 This interface is implemented by the factory
1207 """)
1209class IAdapterRegistration(_IBaseAdapterRegistration):
1210 """Information about the registration of an adapter
1211 """
1213class ISubscriptionAdapterRegistration(_IBaseAdapterRegistration):
1214 """Information about the registration of a subscription adapter
1215 """
1217class IHandlerRegistration(IRegistration):
1219 handler = Attribute("An object called used to handle an event")
1221 required = Attribute("""The handled interfaces
1223 This is a sequence of interfaces handled by the registered
1224 handler. The handler will be caled with a sequence of objects, as
1225 positional arguments, that provide these interfaces.
1226 """)
1228class IRegistrationEvent(IObjectEvent):
1229 """An event that involves a registration"""
1232@implementer(IRegistrationEvent)
1233class RegistrationEvent(ObjectEvent):
1234 """There has been a change in a registration
1235 """
1236 def __repr__(self):
1237 return "%s event:\n%r" % (self.__class__.__name__, self.object)
1239class IRegistered(IRegistrationEvent):
1240 """A component or factory was registered
1241 """
1243@implementer(IRegistered)
1244class Registered(RegistrationEvent):
1245 pass
1247class IUnregistered(IRegistrationEvent):
1248 """A component or factory was unregistered
1249 """
1251@implementer(IUnregistered)
1252class Unregistered(RegistrationEvent):
1253 """A component or factory was unregistered
1254 """
1257class IComponentRegistry(Interface):
1258 """Register components
1259 """
1261 def registerUtility(component=None, provided=None, name=u'',
1262 info=u'', factory=None):
1263 """Register a utility
1265 :param factory:
1266 Factory for the component to be registered.
1268 :param component:
1269 The registered component
1271 :param provided:
1272 This is the interface provided by the utility. If the
1273 component provides a single interface, then this
1274 argument is optional and the component-implemented
1275 interface will be used.
1277 :param name:
1278 The utility name.
1280 :param info:
1281 An object that can be converted to a string to provide
1282 information about the registration.
1284 Only one of *component* and *factory* can be used.
1286 A `IRegistered` event is generated with an `IUtilityRegistration`.
1287 """
1289 def unregisterUtility(component=None, provided=None, name=u'',
1290 factory=None):
1291 """Unregister a utility
1293 :returns:
1294 A boolean is returned indicating whether the registry was
1295 changed. If the given *component* is None and there is no
1296 component registered, or if the given *component* is not
1297 None and is not registered, then the function returns
1298 False, otherwise it returns True.
1300 :param factory:
1301 Factory for the component to be unregistered.
1303 :param component:
1304 The registered component The given component can be
1305 None, in which case any component registered to provide
1306 the given provided interface with the given name is
1307 unregistered.
1309 :param provided:
1310 This is the interface provided by the utility. If the
1311 component is not None and provides a single interface,
1312 then this argument is optional and the
1313 component-implemented interface will be used.
1315 :param name:
1316 The utility name.
1318 Only one of *component* and *factory* can be used.
1319 An `IUnregistered` event is generated with an `IUtilityRegistration`.
1320 """
1322 def registeredUtilities():
1323 """Return an iterable of `IUtilityRegistration` instances.
1325 These registrations describe the current utility registrations
1326 in the object.
1327 """
1329 def registerAdapter(factory, required=None, provided=None, name=u'',
1330 info=u''):
1331 """Register an adapter factory
1333 :param factory:
1334 The object used to compute the adapter
1336 :param required:
1337 This is a sequence of specifications for objects to be
1338 adapted. If omitted, then the value of the factory's
1339 ``__component_adapts__`` attribute will be used. The
1340 ``__component_adapts__`` attribute is
1341 normally set in class definitions using
1342 the `.adapter`
1343 decorator. If the factory doesn't have a
1344 ``__component_adapts__`` adapts attribute, then this
1345 argument is required.
1347 :param provided:
1348 This is the interface provided by the adapter and
1349 implemented by the factory. If the factory
1350 implements a single interface, then this argument is
1351 optional and the factory-implemented interface will be
1352 used.
1354 :param name:
1355 The adapter name.
1357 :param info:
1358 An object that can be converted to a string to provide
1359 information about the registration.
1361 A `IRegistered` event is generated with an `IAdapterRegistration`.
1362 """
1364 def unregisterAdapter(factory=None, required=None,
1365 provided=None, name=u''):
1366 """Unregister an adapter factory
1368 :returns:
1369 A boolean is returned indicating whether the registry was
1370 changed. If the given component is None and there is no
1371 component registered, or if the given component is not
1372 None and is not registered, then the function returns
1373 False, otherwise it returns True.
1375 :param factory:
1376 This is the object used to compute the adapter. The
1377 factory can be None, in which case any factory
1378 registered to implement the given provided interface
1379 for the given required specifications with the given
1380 name is unregistered.
1382 :param required:
1383 This is a sequence of specifications for objects to be
1384 adapted. If the factory is not None and the required
1385 arguments is omitted, then the value of the factory's
1386 __component_adapts__ attribute will be used. The
1387 __component_adapts__ attribute attribute is normally
1388 set in class definitions using adapts function, or for
1389 callables using the adapter decorator. If the factory
1390 is None or doesn't have a __component_adapts__ adapts
1391 attribute, then this argument is required.
1393 :param provided:
1394 This is the interface provided by the adapter and
1395 implemented by the factory. If the factory is not
1396 None and implements a single interface, then this
1397 argument is optional and the factory-implemented
1398 interface will be used.
1400 :param name:
1401 The adapter name.
1403 An `IUnregistered` event is generated with an `IAdapterRegistration`.
1404 """
1406 def registeredAdapters():
1407 """Return an iterable of `IAdapterRegistration` instances.
1409 These registrations describe the current adapter registrations
1410 in the object.
1411 """
1413 def registerSubscriptionAdapter(factory, required=None, provides=None,
1414 name=u'', info=''):
1415 """Register a subscriber factory
1417 :param factory:
1418 The object used to compute the adapter
1420 :param required:
1421 This is a sequence of specifications for objects to be
1422 adapted. If omitted, then the value of the factory's
1423 ``__component_adapts__`` attribute will be used. The
1424 ``__component_adapts__`` attribute is
1425 normally set using the adapter
1426 decorator. If the factory doesn't have a
1427 ``__component_adapts__`` adapts attribute, then this
1428 argument is required.
1430 :param provided:
1431 This is the interface provided by the adapter and
1432 implemented by the factory. If the factory implements
1433 a single interface, then this argument is optional and
1434 the factory-implemented interface will be used.
1436 :param name:
1437 The adapter name.
1439 Currently, only the empty string is accepted. Other
1440 strings will be accepted in the future when support for
1441 named subscribers is added.
1443 :param info:
1444 An object that can be converted to a string to provide
1445 information about the registration.
1447 A `IRegistered` event is generated with an
1448 `ISubscriptionAdapterRegistration`.
1449 """
1451 def unregisterSubscriptionAdapter(factory=None, required=None,
1452 provides=None, name=u''):
1453 """Unregister a subscriber factory.
1455 :returns:
1456 A boolean is returned indicating whether the registry was
1457 changed. If the given component is None and there is no
1458 component registered, or if the given component is not
1459 None and is not registered, then the function returns
1460 False, otherwise it returns True.
1462 :param factory:
1463 This is the object used to compute the adapter. The
1464 factory can be None, in which case any factories
1465 registered to implement the given provided interface
1466 for the given required specifications with the given
1467 name are unregistered.
1469 :param required:
1470 This is a sequence of specifications for objects to be
1471 adapted. If omitted, then the value of the factory's
1472 ``__component_adapts__`` attribute will be used. The
1473 ``__component_adapts__`` attribute is
1474 normally set using the adapter
1475 decorator. If the factory doesn't have a
1476 ``__component_adapts__`` adapts attribute, then this
1477 argument is required.
1479 :param provided:
1480 This is the interface provided by the adapter and
1481 implemented by the factory. If the factory is not
1482 None implements a single interface, then this argument
1483 is optional and the factory-implemented interface will
1484 be used.
1486 :param name:
1487 The adapter name.
1489 Currently, only the empty string is accepted. Other
1490 strings will be accepted in the future when support for
1491 named subscribers is added.
1493 An `IUnregistered` event is generated with an
1494 `ISubscriptionAdapterRegistration`.
1495 """
1497 def registeredSubscriptionAdapters():
1498 """Return an iterable of `ISubscriptionAdapterRegistration` instances.
1500 These registrations describe the current subscription adapter
1501 registrations in the object.
1502 """
1504 def registerHandler(handler, required=None, name=u'', info=''):
1505 """Register a handler.
1507 A handler is a subscriber that doesn't compute an adapter
1508 but performs some function when called.
1510 :param handler:
1511 The object used to handle some event represented by
1512 the objects passed to it.
1514 :param required:
1515 This is a sequence of specifications for objects to be
1516 adapted. If omitted, then the value of the factory's
1517 ``__component_adapts__`` attribute will be used. The
1518 ``__component_adapts__`` attribute is
1519 normally set using the adapter
1520 decorator. If the factory doesn't have a
1521 ``__component_adapts__`` adapts attribute, then this
1522 argument is required.
1524 :param name:
1525 The handler name.
1527 Currently, only the empty string is accepted. Other
1528 strings will be accepted in the future when support for
1529 named handlers is added.
1531 :param info:
1532 An object that can be converted to a string to provide
1533 information about the registration.
1536 A `IRegistered` event is generated with an `IHandlerRegistration`.
1537 """
1539 def unregisterHandler(handler=None, required=None, name=u''):
1540 """Unregister a handler.
1542 A handler is a subscriber that doesn't compute an adapter
1543 but performs some function when called.
1545 :returns: A boolean is returned indicating whether the registry was
1546 changed.
1548 :param handler:
1549 This is the object used to handle some event
1550 represented by the objects passed to it. The handler
1551 can be None, in which case any handlers registered for
1552 the given required specifications with the given are
1553 unregistered.
1555 :param required:
1556 This is a sequence of specifications for objects to be
1557 adapted. If omitted, then the value of the factory's
1558 ``__component_adapts__`` attribute will be used. The
1559 ``__component_adapts__`` attribute is
1560 normally set using the adapter
1561 decorator. If the factory doesn't have a
1562 ``__component_adapts__`` adapts attribute, then this
1563 argument is required.
1565 :param name:
1566 The handler name.
1568 Currently, only the empty string is accepted. Other
1569 strings will be accepted in the future when support for
1570 named handlers is added.
1572 An `IUnregistered` event is generated with an `IHandlerRegistration`.
1573 """
1575 def registeredHandlers():
1576 """Return an iterable of `IHandlerRegistration` instances.
1578 These registrations describe the current handler registrations
1579 in the object.
1580 """
1583class IComponents(IComponentLookup, IComponentRegistry):
1584 """Component registration and access
1585 """
1588# end formerly in zope.component