interfaces.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  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'
  17. from zope.interface.declarations import implementer
  18. from zope.interface.interface import Attribute
  19. from zope.interface.interface import Interface
  20. __all__ = [
  21. 'ComponentLookupError',
  22. 'IAdapterRegistration',
  23. 'IAdapterRegistry',
  24. 'IAttribute',
  25. 'IComponentLookup',
  26. 'IComponentRegistry',
  27. 'IComponents',
  28. 'IDeclaration',
  29. 'IElement',
  30. 'IHandlerRegistration',
  31. 'IInterface',
  32. 'IInterfaceDeclaration',
  33. 'IMethod',
  34. 'Invalid',
  35. 'IObjectEvent',
  36. 'IRegistered',
  37. 'IRegistration',
  38. 'IRegistrationEvent',
  39. 'ISpecification',
  40. 'ISubscriptionAdapterRegistration',
  41. 'IUnregistered',
  42. 'IUtilityRegistration',
  43. 'ObjectEvent',
  44. 'Registered',
  45. 'Unregistered',
  46. ]
  47. # pylint:disable=inherit-non-class,no-method-argument,no-self-argument
  48. # pylint:disable=unexpected-special-method-signature
  49. # pylint:disable=too-many-lines
  50. class IElement(Interface):
  51. """
  52. 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. """
  60. # pylint:disable=arguments-differ
  61. # Note that defining __doc__ as an Attribute hides the docstring
  62. # from introspection. When changing it, also change it in the Sphinx
  63. # ReST files.
  64. __name__ = Attribute('__name__', 'The object name')
  65. __doc__ = Attribute('__doc__', 'The object doc string')
  66. ###
  67. # Tagged values.
  68. #
  69. # Direct values are established in this instance. Others may be
  70. # inherited. Although ``IElement`` itself doesn't have a notion of
  71. # inheritance, ``IInterface`` *does*. It might have been better to
  72. # make ``IInterface`` define new methods
  73. # ``getIndirectTaggedValue``, etc, to include inheritance instead
  74. # of overriding ``getTaggedValue`` to do that, but that ship has sailed.
  75. # So to keep things nice and symmetric, we define the ``Direct`` methods
  76. # here.
  77. ###
  78. def getTaggedValue(tag):
  79. """Returns the value associated with *tag*.
  80. Raise a `KeyError` if the tag isn't set.
  81. If the object has a notion of inheritance, this searches
  82. through the inheritance hierarchy and returns the nearest result.
  83. If there is no such notion, this looks only at this object.
  84. .. versionchanged:: 4.7.0
  85. This method should respect inheritance if present.
  86. """
  87. def queryTaggedValue(tag, default=None):
  88. """
  89. As for `getTaggedValue`, but instead of raising a `KeyError`, returns
  90. *default*.
  91. .. versionchanged:: 4.7.0
  92. This method should respect inheritance if present.
  93. """
  94. def getTaggedValueTags():
  95. """
  96. Returns a collection of all tags in no particular order.
  97. If the object has a notion of inheritance, this
  98. includes all the inherited tagged values. If there is
  99. no such notion, this looks only at this object.
  100. .. versionchanged:: 4.7.0
  101. This method should respect inheritance if present.
  102. """
  103. def setTaggedValue(tag, value):
  104. """
  105. Associates *value* with *key* directly in this object.
  106. """
  107. def getDirectTaggedValue(tag):
  108. """
  109. As for `getTaggedValue`, but never includes inheritance.
  110. .. versionadded:: 5.0.0
  111. """
  112. def queryDirectTaggedValue(tag, default=None):
  113. """
  114. As for `queryTaggedValue`, but never includes inheritance.
  115. .. versionadded:: 5.0.0
  116. """
  117. def getDirectTaggedValueTags():
  118. """
  119. As for `getTaggedValueTags`, but includes only tags directly
  120. set on this object.
  121. .. versionadded:: 5.0.0
  122. """
  123. class IAttribute(IElement):
  124. """Attribute descriptors"""
  125. interface = Attribute('interface',
  126. 'Stores the interface instance in which the '
  127. 'attribute is located.')
  128. class IMethod(IAttribute):
  129. """Method attributes"""
  130. def getSignatureInfo():
  131. """Returns the signature information.
  132. This method returns a dictionary with the following string keys:
  133. - positional
  134. A sequence of the names of positional arguments.
  135. - required
  136. A sequence of the names of required arguments.
  137. - optional
  138. A dictionary mapping argument names to their default values.
  139. - varargs
  140. The name of the varargs argument (or None).
  141. - kwargs
  142. The name of the kwargs argument (or None).
  143. """
  144. def getSignatureString():
  145. """Return a signature string suitable for inclusion in documentation.
  146. This method returns the function signature string. For example, if you
  147. have ``def func(a, b, c=1, d='f')``, then the signature string is
  148. ``"(a, b, c=1, d='f')"``.
  149. """
  150. class ISpecification(Interface):
  151. """Object Behavioral specifications"""
  152. # pylint:disable=arguments-differ
  153. def providedBy(object): # pylint:disable=redefined-builtin
  154. """Test whether the interface is implemented by the object
  155. Return true of the object asserts that it implements the
  156. interface, including asserting that it implements an extended
  157. interface.
  158. """
  159. def implementedBy(class_):
  160. """Test whether the interface is implemented by instances of the class
  161. Return true of the class asserts that its instances implement the
  162. interface, including asserting that they implement an extended
  163. interface.
  164. """
  165. def isOrExtends(other):
  166. """Test whether the specification is or extends another
  167. """
  168. def extends(other, strict=True):
  169. """Test whether a specification extends another
  170. The specification extends other if it has other as a base
  171. interface or if one of it's bases extends other.
  172. If strict is false, then the specification extends itself.
  173. """
  174. def weakref(callback=None):
  175. """Return a weakref to the specification
  176. This method is, regrettably, needed to allow weakrefs to be
  177. computed to security-proxied specifications. While the
  178. zope.interface package does not require zope.security or
  179. zope.proxy, it has to be able to coexist with it.
  180. """
  181. __bases__ = Attribute("""Base specifications
  182. A tuple of specifications from which this specification is
  183. directly derived.
  184. """)
  185. __sro__ = Attribute("""Specification-resolution order
  186. A tuple of the specification and all of it's ancestor
  187. specifications from most specific to least specific. The specification
  188. itself is the first element.
  189. (This is similar to the method-resolution order for new-style classes.)
  190. """)
  191. __iro__ = Attribute("""Interface-resolution order
  192. A tuple of the specification's ancestor interfaces from
  193. most specific to least specific. The specification itself is
  194. included if it is an interface.
  195. (This is similar to the method-resolution order for new-style classes.)
  196. """)
  197. def get(name, default=None):
  198. """Look up the description for a name
  199. If the named attribute is not defined, the default is
  200. returned.
  201. """
  202. class IInterface(ISpecification, IElement):
  203. """Interface objects
  204. Interface objects describe the behavior of an object by containing
  205. useful information about the object. This information includes:
  206. - Prose documentation about the object. In Python terms, this
  207. is called the "doc string" of the interface. In this element,
  208. you describe how the object works in prose language and any
  209. other useful information about the object.
  210. - Descriptions of attributes. Attribute descriptions include
  211. the name of the attribute and prose documentation describing
  212. the attributes usage.
  213. - Descriptions of methods. Method descriptions can include:
  214. - Prose "doc string" documentation about the method and its
  215. usage.
  216. - A description of the methods arguments; how many arguments
  217. are expected, optional arguments and their default values,
  218. the position or arguments in the signature, whether the
  219. method accepts arbitrary arguments and whether the method
  220. accepts arbitrary keyword arguments.
  221. - Optional tagged data. Interface objects (and their attributes and
  222. methods) can have optional, application specific tagged data
  223. associated with them. Examples uses for this are examples,
  224. security assertions, pre/post conditions, and other possible
  225. information you may want to associate with an Interface or its
  226. attributes.
  227. Not all of this information is mandatory. For example, you may
  228. only want the methods of your interface to have prose
  229. documentation and not describe the arguments of the method in
  230. exact detail. Interface objects are flexible and let you give or
  231. take any of these components.
  232. Interfaces are created with the Python class statement using
  233. either `zope.interface.Interface` or another interface, as in::
  234. from zope.interface import Interface
  235. class IMyInterface(Interface):
  236. '''Interface documentation'''
  237. def meth(arg1, arg2):
  238. '''Documentation for meth'''
  239. # Note that there is no self argument
  240. class IMySubInterface(IMyInterface):
  241. '''Interface documentation'''
  242. def meth2():
  243. '''Documentation for meth2'''
  244. You use interfaces in two ways:
  245. - You assert that your object implement the interfaces.
  246. There are several ways that you can declare that an object
  247. provides an interface:
  248. 1. Call `zope.interface.implementer` on your class definition.
  249. 2. Call `zope.interface.directlyProvides` on your object.
  250. 3. Call `zope.interface.classImplements` to declare that instances
  251. of a class implement an interface.
  252. For example::
  253. from zope.interface import classImplements
  254. classImplements(some_class, some_interface)
  255. This approach is useful when it is not an option to modify
  256. the class source. Note that this doesn't affect what the
  257. class itself implements, but only what its instances
  258. implement.
  259. - You query interface meta-data. See the IInterface methods and
  260. attributes for details.
  261. """
  262. # pylint:disable=arguments-differ
  263. def names(all=False): # pylint:disable=redefined-builtin
  264. """Get the interface attribute names
  265. Return a collection of the names of the attributes, including
  266. methods, included in the interface definition.
  267. Normally, only directly defined attributes are included. If
  268. a true positional or keyword argument is given, then
  269. attributes defined by base classes will be included.
  270. """
  271. def namesAndDescriptions(all=False): # pylint:disable=redefined-builtin
  272. """Get the interface attribute names and descriptions
  273. Return a collection of the names and descriptions of the
  274. attributes, including methods, as name-value pairs, included
  275. in the interface definition.
  276. Normally, only directly defined attributes are included. If
  277. a true positional or keyword argument is given, then
  278. attributes defined by base classes will be included.
  279. """
  280. def __getitem__(name):
  281. """Get the description for a name
  282. If the named attribute is not defined, a `KeyError` is raised.
  283. """
  284. def direct(name):
  285. """Get the description for the name if it was defined by the interface
  286. If the interface doesn't define the name, returns None.
  287. """
  288. def validateInvariants(obj, errors=None):
  289. """Validate invariants
  290. Validate object to defined invariants. If errors is None,
  291. raises first Invalid error; if errors is a list, appends all errors
  292. to list, then raises Invalid with the errors as the first element
  293. of the "args" tuple."""
  294. def __contains__(name):
  295. """Test whether the name is defined by the interface"""
  296. def __iter__():
  297. """Return an iterator over the names defined by the interface
  298. The names iterated include all of the names defined by the
  299. interface directly and indirectly by base interfaces.
  300. """
  301. __module__ = Attribute("""The name of the module defining the interface""")
  302. class IDeclaration(ISpecification):
  303. """Interface declaration
  304. Declarations are used to express the interfaces implemented by
  305. classes or provided by objects.
  306. """
  307. def __contains__(interface):
  308. """Test whether an interface is in the specification
  309. Return true if the given interface is one of the interfaces in
  310. the specification and false otherwise.
  311. """
  312. def __iter__():
  313. """Return an iterator for the interfaces in the specification
  314. """
  315. def flattened():
  316. """Return an iterator of all included and extended interfaces
  317. An iterator is returned for all interfaces either included in
  318. or extended by interfaces included in the specifications
  319. without duplicates. The interfaces are in "interface
  320. resolution order". The interface resolution order is such that
  321. base interfaces are listed after interfaces that extend them
  322. and, otherwise, interfaces are included in the order that they
  323. were defined in the specification.
  324. """
  325. def __sub__(interfaces):
  326. """Create an interface specification with some interfaces excluded
  327. The argument can be an interface or an interface
  328. specifications. The interface or interfaces given in a
  329. specification are subtracted from the interface specification.
  330. Removing an interface that is not in the specification does
  331. not raise an error. Doing so has no effect.
  332. Removing an interface also removes sub-interfaces of the interface.
  333. """
  334. def __add__(interfaces):
  335. """Create an interface specification with some interfaces added
  336. The argument can be an interface or an interface
  337. specifications. The interface or interfaces given in a
  338. specification are added to the interface specification.
  339. Adding an interface that is already in the specification does
  340. not raise an error. Doing so has no effect.
  341. """
  342. def __nonzero__():
  343. """Return a true value of the interface specification is non-empty
  344. """
  345. class IInterfaceDeclaration(Interface):
  346. """
  347. Declare and check the interfaces of objects.
  348. The functions defined in this interface are used to declare the
  349. interfaces that objects provide and to query the interfaces that
  350. have been declared.
  351. Interfaces can be declared for objects in two ways:
  352. - Interfaces are declared for instances of the object's class
  353. - Interfaces are declared for the object directly.
  354. The interfaces declared for an object are, therefore, the union of
  355. interfaces declared for the object directly and the interfaces
  356. declared for instances of the object's class.
  357. Note that we say that a class implements the interfaces provided
  358. by it's instances. An instance can also provide interfaces
  359. directly. The interfaces provided by an object are the union of
  360. the interfaces provided directly and the interfaces implemented by
  361. the class.
  362. This interface is implemented by :mod:`zope.interface`.
  363. """
  364. # pylint:disable=arguments-differ
  365. ###
  366. # Defining interfaces
  367. ###
  368. Interface = Attribute("The base class used to create new interfaces")
  369. def taggedValue(key, value):
  370. """
  371. Attach a tagged value to an interface while defining the interface.
  372. This is a way of executing :meth:`IElement.setTaggedValue` from
  373. the definition of the interface. For example::
  374. class IFoo(Interface):
  375. taggedValue('key', 'value')
  376. .. seealso:: `zope.interface.taggedValue`
  377. """
  378. def invariant(checker_function):
  379. """
  380. Attach an invariant checker function to an interface while defining it.
  381. Invariants can later be validated against particular implementations by
  382. calling :meth:`IInterface.validateInvariants`.
  383. For example::
  384. def check_range(ob):
  385. if ob.max < ob.min:
  386. raise ValueError("max value is less than min value")
  387. class IRange(Interface):
  388. min = Attribute("The min value")
  389. max = Attribute("The max value")
  390. invariant(check_range)
  391. .. seealso:: `zope.interface.invariant`
  392. """
  393. def interfacemethod(method):
  394. """
  395. A decorator that transforms a method specification into an
  396. implementation method.
  397. This is used to override methods of ``Interface`` or provide new
  398. methods. Definitions using this decorator will not appear in
  399. :meth:`IInterface.names()`. It is possible to have an implementation
  400. method and a method specification of the same name.
  401. For example::
  402. class IRange(Interface):
  403. @interfacemethod
  404. def __adapt__(self, obj):
  405. if isinstance(obj, range):
  406. # Return the builtin ``range`` as-is
  407. return obj
  408. return super(type(IRange), self).__adapt__(obj)
  409. You can use ``super`` to call the parent class functionality. Note
  410. that the zero-argument version (``super().__adapt__``) works on Python
  411. 3.6 and above, but prior to that the two-argument version must be
  412. used, and the class must be explicitly passed as the first argument.
  413. .. versionadded:: 5.1.0
  414. .. seealso:: `zope.interface.interfacemethod`
  415. """
  416. ###
  417. # Querying interfaces
  418. ###
  419. def providedBy(ob):
  420. """
  421. Return the interfaces provided by an object.
  422. This is the union of the interfaces directly provided by an
  423. object and interfaces implemented by it's class.
  424. The value returned is an `IDeclaration`.
  425. .. seealso:: `zope.interface.providedBy`
  426. """
  427. def implementedBy(class_):
  428. """
  429. Return the interfaces implemented for a class's instances.
  430. The value returned is an `IDeclaration`.
  431. .. seealso:: `zope.interface.implementedBy`
  432. """
  433. ###
  434. # Declaring interfaces
  435. ###
  436. def classImplements(class_, *interfaces):
  437. """
  438. Declare additional interfaces implemented for instances of a class.
  439. The arguments after the class are one or more interfaces or
  440. interface specifications (`IDeclaration` objects).
  441. The interfaces given (including the interfaces in the
  442. specifications) are added to any interfaces previously
  443. declared.
  444. Consider the following example::
  445. class C(A, B):
  446. ...
  447. classImplements(C, I1, I2)
  448. Instances of ``C`` provide ``I1``, ``I2``, and whatever interfaces
  449. instances of ``A`` and ``B`` provide. This is equivalent to::
  450. @implementer(I1, I2)
  451. class C(A, B):
  452. pass
  453. .. seealso:: `zope.interface.classImplements`
  454. .. seealso:: `zope.interface.implementer`
  455. """
  456. def classImplementsFirst(cls, interface):
  457. """
  458. See :func:`zope.interface.classImplementsFirst`.
  459. """
  460. def implementer(*interfaces):
  461. """
  462. Create a decorator for declaring interfaces implemented by a
  463. factory.
  464. A callable is returned that makes an implements declaration on
  465. objects passed to it.
  466. .. seealso:: :meth:`classImplements`
  467. """
  468. def classImplementsOnly(class_, *interfaces):
  469. """
  470. Declare the only interfaces implemented by instances of a class.
  471. The arguments after the class are one or more interfaces or
  472. interface specifications (`IDeclaration` objects).
  473. The interfaces given (including the interfaces in the
  474. specifications) replace any previous declarations.
  475. Consider the following example::
  476. class C(A, B):
  477. ...
  478. classImplements(C, IA, IB. IC)
  479. classImplementsOnly(C. I1, I2)
  480. Instances of ``C`` provide only ``I1``, ``I2``, and regardless of
  481. whatever interfaces instances of ``A`` and ``B`` implement.
  482. .. seealso:: `zope.interface.classImplementsOnly`
  483. """
  484. def implementer_only(*interfaces):
  485. """
  486. Create a decorator for declaring the only interfaces implemented.
  487. A callable is returned that makes an implements declaration on
  488. objects passed to it.
  489. .. seealso:: `zope.interface.implementer_only`
  490. """
  491. def directlyProvidedBy(object): # pylint:disable=redefined-builtin
  492. """
  493. Return the interfaces directly provided by the given object.
  494. The value returned is an `IDeclaration`.
  495. .. seealso:: `zope.interface.directlyProvidedBy`
  496. """
  497. def directlyProvides(
  498. object, *interfaces,
  499. ): # pylint:disable=redefined-builtin
  500. """
  501. Declare interfaces declared directly for an object.
  502. The arguments after the object are one or more interfaces or
  503. interface specifications (`IDeclaration` objects).
  504. .. caution::
  505. The interfaces given (including the interfaces in the
  506. specifications) *replace* interfaces previously
  507. declared for the object. See :meth:`alsoProvides` to add
  508. additional interfaces.
  509. Consider the following example::
  510. class C(A, B):
  511. ...
  512. ob = C()
  513. directlyProvides(ob, I1, I2)
  514. The object, ``ob`` provides ``I1``, ``I2``, and whatever interfaces
  515. instances have been declared for instances of ``C``.
  516. To remove directly provided interfaces, use `directlyProvidedBy` and
  517. subtract the unwanted interfaces. For example::
  518. directlyProvides(ob, directlyProvidedBy(ob)-I2)
  519. removes I2 from the interfaces directly provided by
  520. ``ob``. The object, ``ob`` no longer directly provides ``I2``,
  521. although it might still provide ``I2`` if it's class
  522. implements ``I2``.
  523. To add directly provided interfaces, use `directlyProvidedBy` and
  524. include additional interfaces. For example::
  525. directlyProvides(ob, directlyProvidedBy(ob), I2)
  526. adds I2 to the interfaces directly provided by ob.
  527. .. seealso:: `zope.interface.directlyProvides`
  528. """
  529. def alsoProvides(object, *interfaces): # pylint:disable=redefined-builtin
  530. """
  531. Declare additional interfaces directly for an object.
  532. For example::
  533. alsoProvides(ob, I1)
  534. is equivalent to::
  535. directlyProvides(ob, directlyProvidedBy(ob), I1)
  536. .. seealso:: `zope.interface.alsoProvides`
  537. """
  538. def noLongerProvides(
  539. object, interface,
  540. ): # pylint:disable=redefined-builtin
  541. """
  542. Remove an interface from the list of an object's directly provided
  543. interfaces.
  544. For example::
  545. noLongerProvides(ob, I1)
  546. is equivalent to::
  547. directlyProvides(ob, directlyProvidedBy(ob) - I1)
  548. with the exception that if ``I1`` is an interface that is
  549. provided by ``ob`` through the class's implementation,
  550. `ValueError` is raised.
  551. .. seealso:: `zope.interface.noLongerProvides`
  552. """
  553. def provider(*interfaces):
  554. """
  555. Declare interfaces provided directly by a class.
  556. .. seealso:: `zope.interface.provider`
  557. """
  558. def moduleProvides(*interfaces):
  559. """
  560. Declare interfaces provided by a module.
  561. This function is used in a module definition.
  562. The arguments are one or more interfaces or interface
  563. specifications (`IDeclaration` objects).
  564. The given interfaces (including the interfaces in the
  565. specifications) are used to create the module's direct-object
  566. interface specification. An error will be raised if the module
  567. already has an interface specification. In other words, it is
  568. an error to call this function more than once in a module
  569. definition.
  570. This function is provided for convenience. It provides a more
  571. convenient way to call `directlyProvides` for a module. For example::
  572. moduleImplements(I1)
  573. is equivalent to::
  574. directlyProvides(sys.modules[__name__], I1)
  575. .. seealso:: `zope.interface.moduleProvides`
  576. """
  577. def Declaration(*interfaces):
  578. """
  579. Create an interface specification.
  580. The arguments are one or more interfaces or interface
  581. specifications (`IDeclaration` objects).
  582. A new interface specification (`IDeclaration`) with the given
  583. interfaces is returned.
  584. .. seealso:: `zope.interface.Declaration`
  585. """
  586. class IAdapterRegistry(Interface):
  587. """Provide an interface-based registry for adapters
  588. This registry registers objects that are in some sense "from" a
  589. sequence of specification to an interface and a name.
  590. No specific semantics are assumed for the registered objects,
  591. however, the most common application will be to register factories
  592. that adapt objects providing required specifications to a provided
  593. interface.
  594. """
  595. def register(required, provided, name, value):
  596. """Register a value
  597. A value is registered for a *sequence* of required specifications, a
  598. provided interface, and a name, which must be text.
  599. """
  600. def registered(required, provided, name=''):
  601. """Return the component registered for the given interfaces and name
  602. name must be text.
  603. Unlike the lookup method, this methods won't retrieve
  604. components registered for more specific required interfaces or
  605. less specific provided interfaces.
  606. If no component was registered exactly for the given
  607. interfaces and name, then None is returned.
  608. """
  609. def lookup(required, provided, name='', default=None):
  610. """Lookup a value
  611. A value is looked up based on a *sequence* of required
  612. specifications, a provided interface, and a name, which must be
  613. text.
  614. """
  615. def queryMultiAdapter(objects, provided, name='', default=None):
  616. """Adapt a sequence of objects to a named, provided, interface
  617. """
  618. def lookup1(required, provided, name='', default=None):
  619. """Lookup a value using a single required interface
  620. A value is looked up based on a single required
  621. specifications, a provided interface, and a name, which must be
  622. text.
  623. """
  624. def queryAdapter(
  625. object, provided, name='', default=None,
  626. ): # pylint:disable=redefined-builtin
  627. """Adapt an object using a registered adapter factory.
  628. """
  629. def adapter_hook(
  630. provided, object, name='', default=None,
  631. ): # pylint:disable=redefined-builtin
  632. """Adapt an object using a registered adapter factory.
  633. name must be text.
  634. """
  635. def lookupAll(required, provided):
  636. """Find all adapters from the required to the provided interfaces
  637. An iterable object is returned that provides name-value two-tuples.
  638. """
  639. def names(required, provided): # pylint:disable=arguments-differ
  640. """Return the names for which there are registered objects
  641. """
  642. def subscribe(
  643. required, provided, subscriber,
  644. ): # pylint:disable=arguments-differ
  645. """Register a subscriber
  646. A subscriber is registered for a *sequence* of required
  647. specifications, a provided interface, and a name.
  648. Multiple subscribers may be registered for the same (or
  649. equivalent) interfaces.
  650. .. versionchanged:: 5.1.1
  651. Correct the method signature to remove the ``name`` parameter.
  652. Subscribers have no names.
  653. """
  654. def subscribed(required, provided, subscriber):
  655. """
  656. Check whether the object *subscriber* is registered directly
  657. with this object via a previous call to
  658. ``subscribe(required, provided, subscriber)``.
  659. If the *subscriber*, or one equal to it, has been subscribed,
  660. for the given *required* sequence and *provided* interface,
  661. return that object. (This does not guarantee whether the *subscriber*
  662. itself is returned, or an object equal to it.)
  663. If it has not, return ``None``.
  664. Unlike :meth:`subscriptions`, this method won't retrieve
  665. components registered for more specific required interfaces or
  666. less specific provided interfaces.
  667. .. versionadded:: 5.3.0
  668. """
  669. def subscriptions(required, provided):
  670. """
  671. Get a sequence of subscribers.
  672. Subscribers for a sequence of *required* interfaces, and a *provided*
  673. interface are returned. This takes into account subscribers
  674. registered with this object, as well as those registered with
  675. base adapter registries in the resolution order, and interfaces that
  676. extend *provided*.
  677. .. versionchanged:: 5.1.1
  678. Correct the method signature to remove the ``name`` parameter.
  679. Subscribers have no names.
  680. """
  681. def subscribers(objects, provided):
  682. """
  683. Get a sequence of subscription **adapters**.
  684. This is like :meth:`subscriptions`, but calls the returned
  685. subscribers with *objects* (and optionally returns the results
  686. of those calls), instead of returning the subscribers directly.
  687. :param objects: A sequence of objects; they will be used to
  688. determine the *required* argument to :meth:`subscriptions`.
  689. :param provided: A single interface, or ``None``, to pass
  690. as the *provided* parameter to :meth:`subscriptions`.
  691. If an interface is given, the results of calling each returned
  692. subscriber with the the *objects* are collected and returned
  693. from this method; each result should be an object implementing
  694. the *provided* interface. If ``None``, the resulting subscribers
  695. are still called, but the results are ignored.
  696. :return: A sequence of the results of calling the subscribers
  697. if *provided* is not ``None``. If there are no registered
  698. subscribers, or *provided* is ``None``, this will be an empty
  699. sequence.
  700. .. versionchanged:: 5.1.1
  701. Correct the method signature to remove the ``name`` parameter.
  702. Subscribers have no names.
  703. """
  704. # begin formerly in zope.component
  705. class ComponentLookupError(LookupError):
  706. """A component could not be found."""
  707. class Invalid(Exception):
  708. """A component doesn't satisfy a promise."""
  709. class IObjectEvent(Interface):
  710. """An event related to an object.
  711. The object that generated this event is not necessarily the object
  712. referred to by location.
  713. """
  714. object = Attribute("The subject of the event.")
  715. @implementer(IObjectEvent)
  716. class ObjectEvent:
  717. def __init__(self, object): # pylint:disable=redefined-builtin
  718. self.object = object
  719. class IComponentLookup(Interface):
  720. """Component Manager for a Site
  721. This object manages the components registered at a particular site. The
  722. definition of a site is intentionally vague.
  723. """
  724. adapters = Attribute(
  725. "Adapter Registry to manage all registered adapters.")
  726. utilities = Attribute(
  727. "Adapter Registry to manage all registered utilities.")
  728. def queryAdapter(
  729. object, interface, name='', default=None
  730. ): # pylint:disable=redefined-builtin
  731. """Look for a named adapter to an interface for an object
  732. If a matching adapter cannot be found, returns the default.
  733. """
  734. def getAdapter(
  735. object, interface, name=''
  736. ): # pylint:disable=redefined-builtin
  737. """Look for a named adapter to an interface for an object
  738. If a matching adapter cannot be found, a `ComponentLookupError`
  739. is raised.
  740. """
  741. def queryMultiAdapter(objects, interface, name='', default=None):
  742. """Look for a multi-adapter to an interface for multiple objects
  743. If a matching adapter cannot be found, returns the default.
  744. """
  745. def getMultiAdapter(objects, interface, name=''):
  746. """Look for a multi-adapter to an interface for multiple objects
  747. If a matching adapter cannot be found, a `ComponentLookupError`
  748. is raised.
  749. """
  750. def getAdapters(objects, provided):
  751. """Look for all matching adapters to a provided interface for objects
  752. Return an iterable of name-adapter pairs for adapters that
  753. provide the given interface.
  754. """
  755. def subscribers(objects, provided):
  756. """Get subscribers
  757. Subscribers are returned that provide the provided interface
  758. and that depend on and are computed from the sequence of
  759. required objects.
  760. """
  761. def handle(*objects):
  762. """Call handlers for the given objects
  763. Handlers registered for the given objects are called.
  764. """
  765. def queryUtility(interface, name='', default=None):
  766. """Look up a utility that provides an interface.
  767. If one is not found, returns default.
  768. """
  769. def getUtilitiesFor(interface):
  770. """Look up the registered utilities that provide an interface.
  771. Returns an iterable of name-utility pairs.
  772. """
  773. def getAllUtilitiesRegisteredFor(interface):
  774. """Return all registered utilities for an interface
  775. This includes overridden utilities.
  776. An iterable of utility instances is returned. No names are
  777. returned.
  778. """
  779. class IRegistration(Interface):
  780. """A registration-information object
  781. """
  782. registry = Attribute("The registry having the registration")
  783. name = Attribute("The registration name")
  784. info = Attribute("""Information about the registration
  785. This is information deemed useful to people browsing the
  786. configuration of a system. It could, for example, include
  787. commentary or information about the source of the configuration.
  788. """)
  789. class IUtilityRegistration(IRegistration):
  790. """Information about the registration of a utility
  791. """
  792. factory = Attribute("The factory used to create the utility. Optional.")
  793. component = Attribute("The object registered")
  794. provided = Attribute("The interface provided by the component")
  795. class _IBaseAdapterRegistration(IRegistration):
  796. """Information about the registration of an adapter
  797. """
  798. factory = Attribute("The factory used to create adapters")
  799. required = Attribute("""The adapted interfaces
  800. This is a sequence of interfaces adapters by the registered
  801. factory. The factory will be caled with a sequence of objects, as
  802. positional arguments, that provide these interfaces.
  803. """)
  804. provided = Attribute("""The interface provided by the adapters.
  805. This interface is implemented by the factory
  806. """)
  807. class IAdapterRegistration(_IBaseAdapterRegistration):
  808. """Information about the registration of an adapter
  809. """
  810. class ISubscriptionAdapterRegistration(_IBaseAdapterRegistration):
  811. """Information about the registration of a subscription adapter
  812. """
  813. class IHandlerRegistration(IRegistration):
  814. handler = Attribute("An object called used to handle an event")
  815. required = Attribute("""The handled interfaces
  816. This is a sequence of interfaces handled by the registered
  817. handler. The handler will be caled with a sequence of objects, as
  818. positional arguments, that provide these interfaces.
  819. """)
  820. class IRegistrationEvent(IObjectEvent):
  821. """An event that involves a registration"""
  822. @implementer(IRegistrationEvent)
  823. class RegistrationEvent(ObjectEvent):
  824. """There has been a change in a registration
  825. """
  826. def __repr__(self):
  827. return f"{self.__class__.__name__} event:\n{self.object!r}"
  828. class IRegistered(IRegistrationEvent):
  829. """A component or factory was registered
  830. """
  831. @implementer(IRegistered)
  832. class Registered(RegistrationEvent):
  833. pass
  834. class IUnregistered(IRegistrationEvent):
  835. """A component or factory was unregistered
  836. """
  837. @implementer(IUnregistered)
  838. class Unregistered(RegistrationEvent):
  839. """A component or factory was unregistered
  840. """
  841. class IComponentRegistry(Interface):
  842. """Register components
  843. """
  844. def registerUtility(component=None, provided=None, name='',
  845. info='', factory=None):
  846. """Register a utility
  847. :param factory:
  848. Factory for the component to be registered.
  849. :param component:
  850. The registered component
  851. :param provided:
  852. This is the interface provided by the utility. If the
  853. component provides a single interface, then this
  854. argument is optional and the component-implemented
  855. interface will be used.
  856. :param name:
  857. The utility name.
  858. :param info:
  859. An object that can be converted to a string to provide
  860. information about the registration.
  861. Only one of *component* and *factory* can be used.
  862. A `IRegistered` event is generated with an `IUtilityRegistration`.
  863. """
  864. def unregisterUtility(component=None, provided=None, name='',
  865. factory=None):
  866. """Unregister a utility
  867. :returns:
  868. A boolean is returned indicating whether the registry was
  869. changed. If the given *component* is None and there is no
  870. component registered, or if the given *component* is not
  871. None and is not registered, then the function returns
  872. False, otherwise it returns True.
  873. :param factory:
  874. Factory for the component to be unregistered.
  875. :param component:
  876. The registered component The given component can be
  877. None, in which case any component registered to provide
  878. the given provided interface with the given name is
  879. unregistered.
  880. :param provided:
  881. This is the interface provided by the utility. If the
  882. component is not None and provides a single interface,
  883. then this argument is optional and the
  884. component-implemented interface will be used.
  885. :param name:
  886. The utility name.
  887. Only one of *component* and *factory* can be used.
  888. An `IUnregistered` event is generated with an `IUtilityRegistration`.
  889. """
  890. def registeredUtilities():
  891. """Return an iterable of `IUtilityRegistration` instances.
  892. These registrations describe the current utility registrations
  893. in the object.
  894. """
  895. def registerAdapter(factory, required=None, provided=None, name='',
  896. info=''):
  897. """Register an adapter factory
  898. :param factory:
  899. The object used to compute the adapter
  900. :param required:
  901. This is a sequence of specifications for objects to be
  902. adapted. If omitted, then the value of the factory's
  903. ``__component_adapts__`` attribute will be used. The
  904. ``__component_adapts__`` attribute is
  905. normally set in class definitions using
  906. the `.adapter`
  907. decorator. If the factory doesn't have a
  908. ``__component_adapts__`` adapts attribute, then this
  909. argument is required.
  910. :param provided:
  911. This is the interface provided by the adapter and
  912. implemented by the factory. If the factory
  913. implements a single interface, then this argument is
  914. optional and the factory-implemented interface will be
  915. used.
  916. :param name:
  917. The adapter name.
  918. :param info:
  919. An object that can be converted to a string to provide
  920. information about the registration.
  921. A `IRegistered` event is generated with an `IAdapterRegistration`.
  922. """
  923. def unregisterAdapter(factory=None, required=None,
  924. provided=None, name=''):
  925. """Unregister an adapter factory
  926. :returns:
  927. A boolean is returned indicating whether the registry was
  928. changed. If the given component is None and there is no
  929. component registered, or if the given component is not
  930. None and is not registered, then the function returns
  931. False, otherwise it returns True.
  932. :param factory:
  933. This is the object used to compute the adapter. The
  934. factory can be None, in which case any factory
  935. registered to implement the given provided interface
  936. for the given required specifications with the given
  937. name is unregistered.
  938. :param required:
  939. This is a sequence of specifications for objects to be
  940. adapted. If the factory is not None and the required
  941. arguments is omitted, then the value of the factory's
  942. __component_adapts__ attribute will be used. The
  943. __component_adapts__ attribute attribute is normally
  944. set in class definitions using adapts function, or for
  945. callables using the adapter decorator. If the factory
  946. is None or doesn't have a __component_adapts__ adapts
  947. attribute, then this argument is required.
  948. :param provided:
  949. This is the interface provided by the adapter and
  950. implemented by the factory. If the factory is not
  951. None and implements a single interface, then this
  952. argument is optional and the factory-implemented
  953. interface will be used.
  954. :param name:
  955. The adapter name.
  956. An `IUnregistered` event is generated with an `IAdapterRegistration`.
  957. """
  958. def registeredAdapters():
  959. """Return an iterable of `IAdapterRegistration` instances.
  960. These registrations describe the current adapter registrations
  961. in the object.
  962. """
  963. def registerSubscriptionAdapter(factory, required=None, provides=None,
  964. name='', info=''):
  965. """Register a subscriber factory
  966. :param factory:
  967. The object used to compute the adapter
  968. :param required:
  969. This is a sequence of specifications for objects to be
  970. adapted. If omitted, then the value of the factory's
  971. ``__component_adapts__`` attribute will be used. The
  972. ``__component_adapts__`` attribute is
  973. normally set using the adapter
  974. decorator. If the factory doesn't have a
  975. ``__component_adapts__`` adapts attribute, then this
  976. argument is required.
  977. :param provided:
  978. This is the interface provided by the adapter and
  979. implemented by the factory. If the factory implements
  980. a single interface, then this argument is optional and
  981. the factory-implemented interface will be used.
  982. :param name:
  983. The adapter name.
  984. Currently, only the empty string is accepted. Other
  985. strings will be accepted in the future when support for
  986. named subscribers is added.
  987. :param info:
  988. An object that can be converted to a string to provide
  989. information about the registration.
  990. A `IRegistered` event is generated with an
  991. `ISubscriptionAdapterRegistration`.
  992. """
  993. def unregisterSubscriptionAdapter(factory=None, required=None,
  994. provides=None, name=''):
  995. """Unregister a subscriber factory.
  996. :returns:
  997. A boolean is returned indicating whether the registry was
  998. changed. If the given component is None and there is no
  999. component registered, or if the given component is not
  1000. None and is not registered, then the function returns
  1001. False, otherwise it returns True.
  1002. :param factory:
  1003. This is the object used to compute the adapter. The
  1004. factory can be None, in which case any factories
  1005. registered to implement the given provided interface
  1006. for the given required specifications with the given
  1007. name are unregistered.
  1008. :param required:
  1009. This is a sequence of specifications for objects to be
  1010. adapted. If omitted, then the value of the factory's
  1011. ``__component_adapts__`` attribute will be used. The
  1012. ``__component_adapts__`` attribute is
  1013. normally set using the adapter
  1014. decorator. If the factory doesn't have a
  1015. ``__component_adapts__`` adapts attribute, then this
  1016. argument is required.
  1017. :param provided:
  1018. This is the interface provided by the adapter and
  1019. implemented by the factory. If the factory is not
  1020. None implements a single interface, then this argument
  1021. is optional and the factory-implemented interface will
  1022. be used.
  1023. :param name:
  1024. The adapter name.
  1025. Currently, only the empty string is accepted. Other
  1026. strings will be accepted in the future when support for
  1027. named subscribers is added.
  1028. An `IUnregistered` event is generated with an
  1029. `ISubscriptionAdapterRegistration`.
  1030. """
  1031. def registeredSubscriptionAdapters():
  1032. """Return an iterable of `ISubscriptionAdapterRegistration` instances.
  1033. These registrations describe the current subscription adapter
  1034. registrations in the object.
  1035. """
  1036. def registerHandler(handler, required=None, name='', info=''):
  1037. """Register a handler.
  1038. A handler is a subscriber that doesn't compute an adapter
  1039. but performs some function when called.
  1040. :param handler:
  1041. The object used to handle some event represented by
  1042. the objects passed to it.
  1043. :param required:
  1044. This is a sequence of specifications for objects to be
  1045. adapted. If omitted, then the value of the factory's
  1046. ``__component_adapts__`` attribute will be used. The
  1047. ``__component_adapts__`` attribute is
  1048. normally set using the adapter
  1049. decorator. If the factory doesn't have a
  1050. ``__component_adapts__`` adapts attribute, then this
  1051. argument is required.
  1052. :param name:
  1053. The handler name.
  1054. Currently, only the empty string is accepted. Other
  1055. strings will be accepted in the future when support for
  1056. named handlers is added.
  1057. :param info:
  1058. An object that can be converted to a string to provide
  1059. information about the registration.
  1060. A `IRegistered` event is generated with an `IHandlerRegistration`.
  1061. """
  1062. def unregisterHandler(handler=None, required=None, name=''):
  1063. """Unregister a handler.
  1064. A handler is a subscriber that doesn't compute an adapter
  1065. but performs some function when called.
  1066. :returns: A boolean is returned indicating whether the registry was
  1067. changed.
  1068. :param handler:
  1069. This is the object used to handle some event
  1070. represented by the objects passed to it. The handler
  1071. can be None, in which case any handlers registered for
  1072. the given required specifications with the given are
  1073. unregistered.
  1074. :param required:
  1075. This is a sequence of specifications for objects to be
  1076. adapted. If omitted, then the value of the factory's
  1077. ``__component_adapts__`` attribute will be used. The
  1078. ``__component_adapts__`` attribute is
  1079. normally set using the adapter
  1080. decorator. If the factory doesn't have a
  1081. ``__component_adapts__`` adapts attribute, then this
  1082. argument is required.
  1083. :param name:
  1084. The handler name.
  1085. Currently, only the empty string is accepted. Other
  1086. strings will be accepted in the future when support for
  1087. named handlers is added.
  1088. An `IUnregistered` event is generated with an `IHandlerRegistration`.
  1089. """
  1090. def registeredHandlers():
  1091. """Return an iterable of `IHandlerRegistration` instances.
  1092. These registrations describe the current handler registrations
  1093. in the object.
  1094. """
  1095. class IComponents(IComponentLookup, IComponentRegistry):
  1096. """Component registration and access
  1097. """
  1098. # end formerly in zope.component