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.

adapter.py 35KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2004 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. """Adapter management
  15. """
  16. import itertools
  17. import weakref
  18. from zope.interface import implementer
  19. from zope.interface import providedBy
  20. from zope.interface import Interface
  21. from zope.interface import ro
  22. from zope.interface.interfaces import IAdapterRegistry
  23. from zope.interface._compat import _normalize_name
  24. from zope.interface._compat import _use_c_impl
  25. __all__ = [
  26. 'AdapterRegistry',
  27. 'VerifyingAdapterRegistry',
  28. ]
  29. # In the CPython implementation,
  30. # ``tuple`` and ``list`` cooperate so that ``tuple([some list])``
  31. # directly allocates and iterates at the C level without using a
  32. # Python iterator. That's not the case for
  33. # ``tuple(generator_expression)`` or ``tuple(map(func, it))``.
  34. ##
  35. # 3.8
  36. # ``tuple([t for t in range(10)])`` -> 610ns
  37. # ``tuple(t for t in range(10))`` -> 696ns
  38. # ``tuple(map(lambda t: t, range(10)))`` -> 881ns
  39. ##
  40. # 2.7
  41. # ``tuple([t fon t in range(10)])`` -> 625ns
  42. # ``tuple(t for t in range(10))`` -> 665ns
  43. # ``tuple(map(lambda t: t, range(10)))`` -> 958ns
  44. #
  45. # All three have substantial variance.
  46. ##
  47. # On PyPy, this is also the best option.
  48. ##
  49. # PyPy 2.7.18-7.3.3
  50. # ``tuple([t fon t in range(10)])`` -> 128ns
  51. # ``tuple(t for t in range(10))`` -> 175ns
  52. # ``tuple(map(lambda t: t, range(10)))`` -> 153ns
  53. ##
  54. # PyPy 3.7.9 7.3.3-beta
  55. # ``tuple([t fon t in range(10)])`` -> 82ns
  56. # ``tuple(t for t in range(10))`` -> 177ns
  57. # ``tuple(map(lambda t: t, range(10)))`` -> 168ns
  58. #
  59. class BaseAdapterRegistry:
  60. """
  61. A basic implementation of the data storage and algorithms required
  62. for a :class:`zope.interface.interfaces.IAdapterRegistry`.
  63. Subclasses can set the following attributes to control how the data
  64. is stored; in particular, these hooks can be helpful for ZODB
  65. persistence. They can be class attributes that are the named (or similar) type, or
  66. they can be methods that act as a constructor for an object that behaves
  67. like the types defined here; this object will not assume that they are type
  68. objects, but subclasses are free to do so:
  69. _sequenceType = list
  70. This is the type used for our two mutable top-level "byorder" sequences.
  71. Must support mutation operations like ``append()`` and ``del seq[index]``.
  72. These are usually small (< 10). Although at least one of them is
  73. accessed when performing lookups or queries on this object, the other
  74. is untouched. In many common scenarios, both are only required when
  75. mutating registrations and subscriptions (like what
  76. :meth:`zope.interface.interfaces.IComponents.registerUtility` does).
  77. This use pattern makes it an ideal candidate to be a
  78. :class:`~persistent.list.PersistentList`.
  79. _leafSequenceType = tuple
  80. This is the type used for the leaf sequences of subscribers.
  81. It could be set to a ``PersistentList`` to avoid many unnecessary data
  82. loads when subscribers aren't being used. Mutation operations are directed
  83. through :meth:`_addValueToLeaf` and :meth:`_removeValueFromLeaf`; if you use
  84. a mutable type, you'll need to override those.
  85. _mappingType = dict
  86. This is the mutable mapping type used for the keyed mappings.
  87. A :class:`~persistent.mapping.PersistentMapping`
  88. could be used to help reduce the number of data loads when the registry is large
  89. and parts of it are rarely used. Further reductions in data loads can come from
  90. using a :class:`~BTrees.OOBTree.OOBTree`, but care is required
  91. to be sure that all required/provided
  92. values are fully ordered (e.g., no required or provided values that are classes
  93. can be used).
  94. _providedType = dict
  95. This is the mutable mapping type used for the ``_provided`` mapping.
  96. This is separate from the generic mapping type because the values
  97. are always integers, so one might choose to use a more optimized data
  98. structure such as a :class:`~BTrees.OIBTree.OIBTree`.
  99. The same caveats regarding key types
  100. apply as for ``_mappingType``.
  101. It is possible to also set these on an instance, but because of the need to
  102. potentially also override :meth:`_addValueToLeaf` and :meth:`_removeValueFromLeaf`,
  103. this may be less useful in a persistent scenario; using a subclass is recommended.
  104. .. versionchanged:: 5.3.0
  105. Add support for customizing the way internal data
  106. structures are created.
  107. .. versionchanged:: 5.3.0
  108. Add methods :meth:`rebuild`, :meth:`allRegistrations`
  109. and :meth:`allSubscriptions`.
  110. """
  111. # List of methods copied from lookup sub-objects:
  112. _delegated = ('lookup', 'queryMultiAdapter', 'lookup1', 'queryAdapter',
  113. 'adapter_hook', 'lookupAll', 'names',
  114. 'subscriptions', 'subscribers')
  115. # All registries maintain a generation that can be used by verifying
  116. # registries
  117. _generation = 0
  118. def __init__(self, bases=()):
  119. # The comments here could be improved. Possibly this bit needs
  120. # explaining in a separate document, as the comments here can
  121. # be quite confusing. /regebro
  122. # {order -> {required -> {provided -> {name -> value}}}}
  123. # Here "order" is actually an index in a list, "required" and
  124. # "provided" are interfaces, and "required" is really a nested
  125. # key. So, for example:
  126. # for order == 0 (that is, self._adapters[0]), we have:
  127. # {provided -> {name -> value}}
  128. # but for order == 2 (that is, self._adapters[2]), we have:
  129. # {r1 -> {r2 -> {provided -> {name -> value}}}}
  130. #
  131. self._adapters = self._sequenceType()
  132. # {order -> {required -> {provided -> {name -> [value]}}}}
  133. # where the remarks about adapters above apply
  134. self._subscribers = self._sequenceType()
  135. # Set, with a reference count, keeping track of the interfaces
  136. # for which we have provided components:
  137. self._provided = self._providedType()
  138. # Create ``_v_lookup`` object to perform lookup. We make this a
  139. # separate object to to make it easier to implement just the
  140. # lookup functionality in C. This object keeps track of cache
  141. # invalidation data in two kinds of registries.
  142. # Invalidating registries have caches that are invalidated
  143. # when they or their base registies change. An invalidating
  144. # registry can only have invalidating registries as bases.
  145. # See LookupBaseFallback below for the pertinent logic.
  146. # Verifying registies can't rely on getting invalidation messages,
  147. # so have to check the generations of base registries to determine
  148. # if their cache data are current. See VerifyingBasePy below
  149. # for the pertinent object.
  150. self._createLookup()
  151. # Setting the bases causes the registries described above
  152. # to be initialized (self._setBases -> self.changed ->
  153. # self._v_lookup.changed).
  154. self.__bases__ = bases
  155. def _setBases(self, bases):
  156. """
  157. If subclasses need to track when ``__bases__`` changes, they
  158. can override this method.
  159. Subclasses must still call this method.
  160. """
  161. self.__dict__['__bases__'] = bases
  162. self.ro = ro.ro(self)
  163. self.changed(self)
  164. __bases__ = property(lambda self: self.__dict__['__bases__'],
  165. lambda self, bases: self._setBases(bases),
  166. )
  167. def _createLookup(self):
  168. self._v_lookup = self.LookupClass(self)
  169. for name in self._delegated:
  170. self.__dict__[name] = getattr(self._v_lookup, name)
  171. # Hooks for subclasses to define the types of objects used in
  172. # our data structures.
  173. # These have to be documented in the docstring, instead of local
  174. # comments, because Sphinx autodoc ignores the comment and just writes
  175. # "alias of list"
  176. _sequenceType = list
  177. _leafSequenceType = tuple
  178. _mappingType = dict
  179. _providedType = dict
  180. def _addValueToLeaf(self, existing_leaf_sequence, new_item):
  181. """
  182. Add the value *new_item* to the *existing_leaf_sequence*, which may
  183. be ``None``.
  184. Subclasses that redefine `_leafSequenceType` should override this method.
  185. :param existing_leaf_sequence:
  186. If *existing_leaf_sequence* is not *None*, it will be an instance
  187. of `_leafSequenceType`. (Unless the object has been unpickled
  188. from an old pickle and the class definition has changed, in which case
  189. it may be an instance of a previous definition, commonly a `tuple`.)
  190. :return:
  191. This method returns the new value to be stored. It may mutate the
  192. sequence in place if it was not ``None`` and the type is mutable, but
  193. it must also return it.
  194. .. versionadded:: 5.3.0
  195. """
  196. if existing_leaf_sequence is None:
  197. return (new_item,)
  198. return existing_leaf_sequence + (new_item,)
  199. def _removeValueFromLeaf(self, existing_leaf_sequence, to_remove):
  200. """
  201. Remove the item *to_remove* from the (non-``None``, non-empty)
  202. *existing_leaf_sequence* and return the mutated sequence.
  203. If there is more than one item that is equal to *to_remove*
  204. they must all be removed.
  205. Subclasses that redefine `_leafSequenceType` should override
  206. this method. Note that they can call this method to help
  207. in their implementation; this implementation will always
  208. return a new tuple constructed by iterating across
  209. the *existing_leaf_sequence* and omitting items equal to *to_remove*.
  210. :param existing_leaf_sequence:
  211. As for `_addValueToLeaf`, probably an instance of
  212. `_leafSequenceType` but possibly an older type; never `None`.
  213. :return:
  214. A version of *existing_leaf_sequence* with all items equal to
  215. *to_remove* removed. Must not return `None`. However,
  216. returning an empty
  217. object, even of another type such as the empty tuple, ``()`` is
  218. explicitly allowed; such an object will never be stored.
  219. .. versionadded:: 5.3.0
  220. """
  221. return tuple([v for v in existing_leaf_sequence if v != to_remove])
  222. def changed(self, originally_changed):
  223. self._generation += 1
  224. self._v_lookup.changed(originally_changed)
  225. def register(self, required, provided, name, value):
  226. if not isinstance(name, str):
  227. raise ValueError('name is not a string')
  228. if value is None:
  229. self.unregister(required, provided, name, value)
  230. return
  231. required = tuple([_convert_None_to_Interface(r) for r in required])
  232. name = _normalize_name(name)
  233. order = len(required)
  234. byorder = self._adapters
  235. while len(byorder) <= order:
  236. byorder.append(self._mappingType())
  237. components = byorder[order]
  238. key = required + (provided,)
  239. for k in key:
  240. d = components.get(k)
  241. if d is None:
  242. d = self._mappingType()
  243. components[k] = d
  244. components = d
  245. if components.get(name) is value:
  246. return
  247. components[name] = value
  248. n = self._provided.get(provided, 0) + 1
  249. self._provided[provided] = n
  250. if n == 1:
  251. self._v_lookup.add_extendor(provided)
  252. self.changed(self)
  253. def _find_leaf(self, byorder, required, provided, name):
  254. # Find the leaf value, if any, in the *byorder* list
  255. # for the interface sequence *required* and the interface
  256. # *provided*, given the already normalized *name*.
  257. #
  258. # If no such leaf value exists, returns ``None``
  259. required = tuple([_convert_None_to_Interface(r) for r in required])
  260. order = len(required)
  261. if len(byorder) <= order:
  262. return None
  263. components = byorder[order]
  264. key = required + (provided,)
  265. for k in key:
  266. d = components.get(k)
  267. if d is None:
  268. return None
  269. components = d
  270. return components.get(name)
  271. def registered(self, required, provided, name=''):
  272. return self._find_leaf(
  273. self._adapters,
  274. required,
  275. provided,
  276. _normalize_name(name)
  277. )
  278. @classmethod
  279. def _allKeys(cls, components, i, parent_k=()):
  280. if i == 0:
  281. for k, v in components.items():
  282. yield parent_k + (k,), v
  283. else:
  284. for k, v in components.items():
  285. new_parent_k = parent_k + (k,)
  286. yield from cls._allKeys(v, i - 1, new_parent_k)
  287. def _all_entries(self, byorder):
  288. # Recurse through the mapping levels of the `byorder` sequence,
  289. # reconstructing a flattened sequence of ``(required, provided, name, value)``
  290. # tuples that can be used to reconstruct the sequence with the appropriate
  291. # registration methods.
  292. #
  293. # Locally reference the `byorder` data; it might be replaced while
  294. # this method is running (see ``rebuild``).
  295. for i, components in enumerate(byorder):
  296. # We will have *i* levels of dictionaries to go before
  297. # we get to the leaf.
  298. for key, value in self._allKeys(components, i + 1):
  299. assert len(key) == i + 2
  300. required = key[:i]
  301. provided = key[-2]
  302. name = key[-1]
  303. yield (required, provided, name, value)
  304. def allRegistrations(self):
  305. """
  306. Yields tuples ``(required, provided, name, value)`` for all
  307. the registrations that this object holds.
  308. These tuples could be passed as the arguments to the
  309. :meth:`register` method on another adapter registry to
  310. duplicate the registrations this object holds.
  311. .. versionadded:: 5.3.0
  312. """
  313. yield from self._all_entries(self._adapters)
  314. def unregister(self, required, provided, name, value=None):
  315. required = tuple([_convert_None_to_Interface(r) for r in required])
  316. order = len(required)
  317. byorder = self._adapters
  318. if order >= len(byorder):
  319. return False
  320. components = byorder[order]
  321. key = required + (provided,)
  322. # Keep track of how we got to `components`:
  323. lookups = []
  324. for k in key:
  325. d = components.get(k)
  326. if d is None:
  327. return
  328. lookups.append((components, k))
  329. components = d
  330. old = components.get(name)
  331. if old is None:
  332. return
  333. if (value is not None) and (old is not value):
  334. return
  335. del components[name]
  336. if not components:
  337. # Clean out empty containers, since we don't want our keys
  338. # to reference global objects (interfaces) unnecessarily.
  339. # This is often a problem when an interface is slated for
  340. # removal; a hold-over entry in the registry can make it
  341. # difficult to remove such interfaces.
  342. for comp, k in reversed(lookups):
  343. d = comp[k]
  344. if d:
  345. break
  346. else:
  347. del comp[k]
  348. while byorder and not byorder[-1]:
  349. del byorder[-1]
  350. n = self._provided[provided] - 1
  351. if n == 0:
  352. del self._provided[provided]
  353. self._v_lookup.remove_extendor(provided)
  354. else:
  355. self._provided[provided] = n
  356. self.changed(self)
  357. def subscribe(self, required, provided, value):
  358. required = tuple([_convert_None_to_Interface(r) for r in required])
  359. name = ''
  360. order = len(required)
  361. byorder = self._subscribers
  362. while len(byorder) <= order:
  363. byorder.append(self._mappingType())
  364. components = byorder[order]
  365. key = required + (provided,)
  366. for k in key:
  367. d = components.get(k)
  368. if d is None:
  369. d = self._mappingType()
  370. components[k] = d
  371. components = d
  372. components[name] = self._addValueToLeaf(components.get(name), value)
  373. if provided is not None:
  374. n = self._provided.get(provided, 0) + 1
  375. self._provided[provided] = n
  376. if n == 1:
  377. self._v_lookup.add_extendor(provided)
  378. self.changed(self)
  379. def subscribed(self, required, provided, subscriber):
  380. subscribers = self._find_leaf(
  381. self._subscribers,
  382. required,
  383. provided,
  384. ''
  385. ) or ()
  386. return subscriber if subscriber in subscribers else None
  387. def allSubscriptions(self):
  388. """
  389. Yields tuples ``(required, provided, value)`` for all the
  390. subscribers that this object holds.
  391. These tuples could be passed as the arguments to the
  392. :meth:`subscribe` method on another adapter registry to
  393. duplicate the registrations this object holds.
  394. .. versionadded:: 5.3.0
  395. """
  396. for required, provided, _name, value in self._all_entries(self._subscribers):
  397. for v in value:
  398. yield (required, provided, v)
  399. def unsubscribe(self, required, provided, value=None):
  400. required = tuple([_convert_None_to_Interface(r) for r in required])
  401. order = len(required)
  402. byorder = self._subscribers
  403. if order >= len(byorder):
  404. return
  405. components = byorder[order]
  406. key = required + (provided,)
  407. # Keep track of how we got to `components`:
  408. lookups = []
  409. for k in key:
  410. d = components.get(k)
  411. if d is None:
  412. return
  413. lookups.append((components, k))
  414. components = d
  415. old = components.get('')
  416. if not old:
  417. # this is belt-and-suspenders against the failure of cleanup below
  418. return # pragma: no cover
  419. len_old = len(old)
  420. if value is None:
  421. # Removing everything; note that the type of ``new`` won't
  422. # necessarily match the ``_leafSequenceType``, but that's
  423. # OK because we're about to delete the entire entry
  424. # anyway.
  425. new = ()
  426. else:
  427. new = self._removeValueFromLeaf(old, value)
  428. # ``new`` may be the same object as ``old``, just mutated in place,
  429. # so we cannot compare it to ``old`` to check for changes. Remove
  430. # our reference to it now to avoid trying to do so below.
  431. del old
  432. if len(new) == len_old:
  433. # No changes, so nothing could have been removed.
  434. return
  435. if new:
  436. components[''] = new
  437. else:
  438. # Instead of setting components[u''] = new, we clean out
  439. # empty containers, since we don't want our keys to
  440. # reference global objects (interfaces) unnecessarily. This
  441. # is often a problem when an interface is slated for
  442. # removal; a hold-over entry in the registry can make it
  443. # difficult to remove such interfaces.
  444. del components['']
  445. for comp, k in reversed(lookups):
  446. d = comp[k]
  447. if d:
  448. break
  449. else:
  450. del comp[k]
  451. while byorder and not byorder[-1]:
  452. del byorder[-1]
  453. if provided is not None:
  454. n = self._provided[provided] + len(new) - len_old
  455. if n == 0:
  456. del self._provided[provided]
  457. self._v_lookup.remove_extendor(provided)
  458. else:
  459. self._provided[provided] = n
  460. self.changed(self)
  461. def rebuild(self):
  462. """
  463. Rebuild (and replace) all the internal data structures of this
  464. object.
  465. This is useful, especially for persistent implementations, if
  466. you suspect an issue with reference counts keeping interfaces
  467. alive even though they are no longer used.
  468. It is also useful if you or a subclass change the data types
  469. (``_mappingType`` and friends) that are to be used.
  470. This method replaces all internal data structures with new objects;
  471. it specifically does not re-use any storage.
  472. .. versionadded:: 5.3.0
  473. """
  474. # Grab the iterators, we're about to discard their data.
  475. registrations = self.allRegistrations()
  476. subscriptions = self.allSubscriptions()
  477. def buffer(it):
  478. # The generator doesn't actually start running until we
  479. # ask for its next(), by which time the attributes will change
  480. # unless we do so before calling __init__.
  481. try:
  482. first = next(it)
  483. except StopIteration:
  484. return iter(())
  485. return itertools.chain((first,), it)
  486. registrations = buffer(registrations)
  487. subscriptions = buffer(subscriptions)
  488. # Replace the base data structures as well as _v_lookup.
  489. self.__init__(self.__bases__)
  490. # Re-register everything previously registered and subscribed.
  491. #
  492. # XXX: This is going to call ``self.changed()`` a lot, all of
  493. # which is unnecessary (because ``self.__init__`` just
  494. # re-created those dependent objects and also called
  495. # ``self.changed()``). Is this a bottleneck that needs fixed?
  496. # (We could do ``self.changed = lambda _: None`` before
  497. # beginning and remove it after to disable the presumably expensive
  498. # part of passing that notification to the change of objects.)
  499. for args in registrations:
  500. self.register(*args)
  501. for args in subscriptions:
  502. self.subscribe(*args)
  503. # XXX hack to fake out twisted's use of a private api. We need to get them
  504. # to use the new registered method.
  505. def get(self, _): # pragma: no cover
  506. class XXXTwistedFakeOut:
  507. selfImplied = {}
  508. return XXXTwistedFakeOut
  509. _not_in_mapping = object()
  510. @_use_c_impl
  511. class LookupBase:
  512. def __init__(self):
  513. self._cache = {}
  514. self._mcache = {}
  515. self._scache = {}
  516. def changed(self, ignored=None):
  517. self._cache.clear()
  518. self._mcache.clear()
  519. self._scache.clear()
  520. def _getcache(self, provided, name):
  521. cache = self._cache.get(provided)
  522. if cache is None:
  523. cache = {}
  524. self._cache[provided] = cache
  525. if name:
  526. c = cache.get(name)
  527. if c is None:
  528. c = {}
  529. cache[name] = c
  530. cache = c
  531. return cache
  532. def lookup(self, required, provided, name='', default=None):
  533. if not isinstance(name, str):
  534. raise ValueError('name is not a string')
  535. cache = self._getcache(provided, name)
  536. required = tuple(required)
  537. if len(required) == 1:
  538. result = cache.get(required[0], _not_in_mapping)
  539. else:
  540. result = cache.get(tuple(required), _not_in_mapping)
  541. if result is _not_in_mapping:
  542. result = self._uncached_lookup(required, provided, name)
  543. if len(required) == 1:
  544. cache[required[0]] = result
  545. else:
  546. cache[tuple(required)] = result
  547. if result is None:
  548. return default
  549. return result
  550. def lookup1(self, required, provided, name='', default=None):
  551. if not isinstance(name, str):
  552. raise ValueError('name is not a string')
  553. cache = self._getcache(provided, name)
  554. result = cache.get(required, _not_in_mapping)
  555. if result is _not_in_mapping:
  556. return self.lookup((required, ), provided, name, default)
  557. if result is None:
  558. return default
  559. return result
  560. def queryAdapter(self, object, provided, name='', default=None):
  561. return self.adapter_hook(provided, object, name, default)
  562. def adapter_hook(self, provided, object, name='', default=None):
  563. if not isinstance(name, str):
  564. raise ValueError('name is not a string')
  565. required = providedBy(object)
  566. cache = self._getcache(provided, name)
  567. factory = cache.get(required, _not_in_mapping)
  568. if factory is _not_in_mapping:
  569. factory = self.lookup((required, ), provided, name)
  570. if factory is not None:
  571. if isinstance(object, super):
  572. object = object.__self__
  573. result = factory(object)
  574. if result is not None:
  575. return result
  576. return default
  577. def lookupAll(self, required, provided):
  578. cache = self._mcache.get(provided)
  579. if cache is None:
  580. cache = {}
  581. self._mcache[provided] = cache
  582. required = tuple(required)
  583. result = cache.get(required, _not_in_mapping)
  584. if result is _not_in_mapping:
  585. result = self._uncached_lookupAll(required, provided)
  586. cache[required] = result
  587. return result
  588. def subscriptions(self, required, provided):
  589. cache = self._scache.get(provided)
  590. if cache is None:
  591. cache = {}
  592. self._scache[provided] = cache
  593. required = tuple(required)
  594. result = cache.get(required, _not_in_mapping)
  595. if result is _not_in_mapping:
  596. result = self._uncached_subscriptions(required, provided)
  597. cache[required] = result
  598. return result
  599. @_use_c_impl
  600. class VerifyingBase(LookupBaseFallback):
  601. # Mixin for lookups against registries which "chain" upwards, and
  602. # whose lookups invalidate their own caches whenever a parent registry
  603. # bumps its own '_generation' counter. E.g., used by
  604. # zope.component.persistentregistry
  605. def changed(self, originally_changed):
  606. LookupBaseFallback.changed(self, originally_changed)
  607. self._verify_ro = self._registry.ro[1:]
  608. self._verify_generations = [r._generation for r in self._verify_ro]
  609. def _verify(self):
  610. if ([r._generation for r in self._verify_ro]
  611. != self._verify_generations):
  612. self.changed(None)
  613. def _getcache(self, provided, name):
  614. self._verify()
  615. return LookupBaseFallback._getcache(self, provided, name)
  616. def lookupAll(self, required, provided):
  617. self._verify()
  618. return LookupBaseFallback.lookupAll(self, required, provided)
  619. def subscriptions(self, required, provided):
  620. self._verify()
  621. return LookupBaseFallback.subscriptions(self, required, provided)
  622. class AdapterLookupBase:
  623. def __init__(self, registry):
  624. self._registry = registry
  625. self._required = {}
  626. self.init_extendors()
  627. super().__init__()
  628. def changed(self, ignored=None):
  629. super().changed(None)
  630. for r in self._required.keys():
  631. r = r()
  632. if r is not None:
  633. r.unsubscribe(self)
  634. self._required.clear()
  635. # Extendors
  636. # ---------
  637. # When given an target interface for an adapter lookup, we need to consider
  638. # adapters for interfaces that extend the target interface. This is
  639. # what the extendors dictionary is about. It tells us all of the
  640. # interfaces that extend an interface for which there are adapters
  641. # registered.
  642. # We could separate this by order and name, thus reducing the
  643. # number of provided interfaces to search at run time. The tradeoff,
  644. # however, is that we have to store more information. For example,
  645. # if the same interface is provided for multiple names and if the
  646. # interface extends many interfaces, we'll have to keep track of
  647. # a fair bit of information for each name. It's better to
  648. # be space efficient here and be time efficient in the cache
  649. # implementation.
  650. # TODO: add invalidation when a provided interface changes, in case
  651. # the interface's __iro__ has changed. This is unlikely enough that
  652. # we'll take our chances for now.
  653. def init_extendors(self):
  654. self._extendors = {}
  655. for p in self._registry._provided:
  656. self.add_extendor(p)
  657. def add_extendor(self, provided):
  658. _extendors = self._extendors
  659. for i in provided.__iro__:
  660. extendors = _extendors.get(i, ())
  661. _extendors[i] = (
  662. [e for e in extendors if provided.isOrExtends(e)]
  663. +
  664. [provided]
  665. +
  666. [e for e in extendors if not provided.isOrExtends(e)]
  667. )
  668. def remove_extendor(self, provided):
  669. _extendors = self._extendors
  670. for i in provided.__iro__:
  671. _extendors[i] = [e for e in _extendors.get(i, ())
  672. if e != provided]
  673. def _subscribe(self, *required):
  674. _refs = self._required
  675. for r in required:
  676. ref = r.weakref()
  677. if ref not in _refs:
  678. r.subscribe(self)
  679. _refs[ref] = 1
  680. def _uncached_lookup(self, required, provided, name=''):
  681. required = tuple(required)
  682. result = None
  683. order = len(required)
  684. for registry in self._registry.ro:
  685. byorder = registry._adapters
  686. if order >= len(byorder):
  687. continue
  688. extendors = registry._v_lookup._extendors.get(provided)
  689. if not extendors:
  690. continue
  691. components = byorder[order]
  692. result = _lookup(components, required, extendors, name, 0,
  693. order)
  694. if result is not None:
  695. break
  696. self._subscribe(*required)
  697. return result
  698. def queryMultiAdapter(self, objects, provided, name='', default=None):
  699. factory = self.lookup([providedBy(o) for o in objects], provided, name)
  700. if factory is None:
  701. return default
  702. result = factory(*[o.__self__ if isinstance(o, super) else o for o in objects])
  703. if result is None:
  704. return default
  705. return result
  706. def _uncached_lookupAll(self, required, provided):
  707. required = tuple(required)
  708. order = len(required)
  709. result = {}
  710. for registry in reversed(self._registry.ro):
  711. byorder = registry._adapters
  712. if order >= len(byorder):
  713. continue
  714. extendors = registry._v_lookup._extendors.get(provided)
  715. if not extendors:
  716. continue
  717. components = byorder[order]
  718. _lookupAll(components, required, extendors, result, 0, order)
  719. self._subscribe(*required)
  720. return tuple(result.items())
  721. def names(self, required, provided):
  722. return [c[0] for c in self.lookupAll(required, provided)]
  723. def _uncached_subscriptions(self, required, provided):
  724. required = tuple(required)
  725. order = len(required)
  726. result = []
  727. for registry in reversed(self._registry.ro):
  728. byorder = registry._subscribers
  729. if order >= len(byorder):
  730. continue
  731. if provided is None:
  732. extendors = (provided, )
  733. else:
  734. extendors = registry._v_lookup._extendors.get(provided)
  735. if extendors is None:
  736. continue
  737. _subscriptions(byorder[order], required, extendors, '',
  738. result, 0, order)
  739. self._subscribe(*required)
  740. return result
  741. def subscribers(self, objects, provided):
  742. subscriptions = self.subscriptions([providedBy(o) for o in objects], provided)
  743. if provided is None:
  744. result = ()
  745. for subscription in subscriptions:
  746. subscription(*objects)
  747. else:
  748. result = []
  749. for subscription in subscriptions:
  750. subscriber = subscription(*objects)
  751. if subscriber is not None:
  752. result.append(subscriber)
  753. return result
  754. class AdapterLookup(AdapterLookupBase, LookupBase):
  755. pass
  756. @implementer(IAdapterRegistry)
  757. class AdapterRegistry(BaseAdapterRegistry):
  758. """
  759. A full implementation of ``IAdapterRegistry`` that adds support for
  760. sub-registries.
  761. """
  762. LookupClass = AdapterLookup
  763. def __init__(self, bases=()):
  764. # AdapterRegisties are invalidating registries, so
  765. # we need to keep track of our invalidating subregistries.
  766. self._v_subregistries = weakref.WeakKeyDictionary()
  767. super().__init__(bases)
  768. def _addSubregistry(self, r):
  769. self._v_subregistries[r] = 1
  770. def _removeSubregistry(self, r):
  771. if r in self._v_subregistries:
  772. del self._v_subregistries[r]
  773. def _setBases(self, bases):
  774. old = self.__dict__.get('__bases__', ())
  775. for r in old:
  776. if r not in bases:
  777. r._removeSubregistry(self)
  778. for r in bases:
  779. if r not in old:
  780. r._addSubregistry(self)
  781. super()._setBases(bases)
  782. def changed(self, originally_changed):
  783. super().changed(originally_changed)
  784. for sub in self._v_subregistries.keys():
  785. sub.changed(originally_changed)
  786. class VerifyingAdapterLookup(AdapterLookupBase, VerifyingBase):
  787. pass
  788. @implementer(IAdapterRegistry)
  789. class VerifyingAdapterRegistry(BaseAdapterRegistry):
  790. """
  791. The most commonly-used adapter registry.
  792. """
  793. LookupClass = VerifyingAdapterLookup
  794. def _convert_None_to_Interface(x):
  795. if x is None:
  796. return Interface
  797. else:
  798. return x
  799. def _lookup(components, specs, provided, name, i, l):
  800. # this function is called very often.
  801. # The components.get in loops is executed 100 of 1000s times.
  802. # by loading get into a local variable the bytecode
  803. # "LOAD_FAST 0 (components)" in the loop can be eliminated.
  804. components_get = components.get
  805. if i < l:
  806. for spec in specs[i].__sro__:
  807. comps = components_get(spec)
  808. if comps:
  809. r = _lookup(comps, specs, provided, name, i+1, l)
  810. if r is not None:
  811. return r
  812. else:
  813. for iface in provided:
  814. comps = components_get(iface)
  815. if comps:
  816. r = comps.get(name)
  817. if r is not None:
  818. return r
  819. return None
  820. def _lookupAll(components, specs, provided, result, i, l):
  821. components_get = components.get # see _lookup above
  822. if i < l:
  823. for spec in reversed(specs[i].__sro__):
  824. comps = components_get(spec)
  825. if comps:
  826. _lookupAll(comps, specs, provided, result, i+1, l)
  827. else:
  828. for iface in reversed(provided):
  829. comps = components_get(iface)
  830. if comps:
  831. result.update(comps)
  832. def _subscriptions(components, specs, provided, name, result, i, l):
  833. components_get = components.get # see _lookup above
  834. if i < l:
  835. for spec in reversed(specs[i].__sro__):
  836. comps = components_get(spec)
  837. if comps:
  838. _subscriptions(comps, specs, provided, name, result, i+1, l)
  839. else:
  840. for iface in reversed(provided):
  841. comps = components_get(iface)
  842. if comps:
  843. comps = comps.get(name)
  844. if comps:
  845. result.extend(comps)