adapter.py 36 KB

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