adapter.py 36 KB

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