Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

interfaces.py 49KB

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