declarations.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. ##############################################################################
  2. # Copyright (c) 2003 Zope Foundation and Contributors.
  3. # All Rights Reserved.
  4. #
  5. # This software is subject to the provisions of the Zope Public License,
  6. # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
  7. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  8. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  9. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  10. # FOR A PARTICULAR PURPOSE.
  11. ##############################################################################
  12. """Implementation of interface declarations
  13. There are three flavors of declarations:
  14. - Declarations are used to simply name declared interfaces.
  15. - ImplementsDeclarations are used to express the interfaces that a
  16. class implements (that instances of the class provides).
  17. Implements specifications support inheriting interfaces.
  18. - ProvidesDeclarations are used to express interfaces directly
  19. provided by objects.
  20. """
  21. __docformat__ = 'restructuredtext'
  22. import sys
  23. import weakref
  24. from types import FunctionType
  25. from types import MethodType
  26. from types import ModuleType
  27. from zope.interface._compat import _use_c_impl
  28. from zope.interface.interface import Interface
  29. from zope.interface.interface import InterfaceBase
  30. from zope.interface.interface import InterfaceClass
  31. from zope.interface.interface import NameAndModuleComparisonMixin
  32. from zope.interface.interface import Specification
  33. from zope.interface.interface import SpecificationBase
  34. __all__ = [
  35. # None. The public APIs of this module are
  36. # re-exported from zope.interface directly.
  37. ]
  38. # pylint:disable=too-many-lines
  39. # Registry of class-implementation specifications
  40. BuiltinImplementationSpecifications = {}
  41. def _next_super_class(ob):
  42. # When ``ob`` is an instance of ``super``, return
  43. # the next class in the MRO that we should actually be
  44. # looking at. Watch out for diamond inheritance!
  45. self_class = ob.__self_class__
  46. class_that_invoked_super = ob.__thisclass__
  47. complete_mro = self_class.__mro__
  48. next_class = complete_mro[complete_mro.index(class_that_invoked_super) + 1]
  49. return next_class
  50. class named:
  51. def __init__(self, name):
  52. self.name = name
  53. def __call__(self, ob):
  54. ob.__component_name__ = self.name
  55. return ob
  56. class Declaration(Specification):
  57. """Interface declarations"""
  58. __slots__ = ()
  59. def __init__(self, *bases):
  60. Specification.__init__(self, _normalizeargs(bases))
  61. def __contains__(self, interface):
  62. """Test whether an interface is in the specification
  63. """
  64. return self.extends(interface) and interface in self.interfaces()
  65. def __iter__(self):
  66. """Return an iterator for the interfaces in the specification
  67. """
  68. return self.interfaces()
  69. def flattened(self):
  70. """Return an iterator of all included and extended interfaces
  71. """
  72. return iter(self.__iro__)
  73. def __sub__(self, other):
  74. """Remove interfaces from a specification
  75. """
  76. return Declaration(*[
  77. i for i in self.interfaces()
  78. if not [
  79. j
  80. for j in other.interfaces()
  81. if i.extends(j, 0) # non-strict extends
  82. ]
  83. ])
  84. def __add__(self, other):
  85. """
  86. Add two specifications or a specification and an interface
  87. and produce a new declaration.
  88. .. versionchanged:: 5.4.0
  89. Now tries to preserve a consistent resolution order. Interfaces
  90. being added to this object are added to the front of the resulting
  91. resolution order if they already extend an interface in this
  92. object. Previously, they were always added to the end of the order,
  93. which easily resulted in invalid orders.
  94. """
  95. before = []
  96. result = list(self.interfaces())
  97. seen = set(result)
  98. for i in other.interfaces():
  99. if i in seen:
  100. continue
  101. seen.add(i)
  102. if any(i.extends(x) for x in result):
  103. # It already extends us, e.g., is a subclass,
  104. # so it needs to go at the front of the RO.
  105. before.append(i)
  106. else:
  107. result.append(i)
  108. return Declaration(*(before + result))
  109. # XXX: Is __radd__ needed? No tests break if it's removed.
  110. # If it is needed, does it need to handle the C3 ordering differently?
  111. # I (JAM) don't *think* it does.
  112. __radd__ = __add__
  113. @staticmethod
  114. def _add_interfaces_to_cls(interfaces, cls):
  115. # Strip redundant interfaces already provided
  116. # by the cls so we don't produce invalid
  117. # resolution orders.
  118. implemented_by_cls = implementedBy(cls)
  119. interfaces = tuple([
  120. iface
  121. for iface in interfaces
  122. if not implemented_by_cls.isOrExtends(iface)
  123. ])
  124. return interfaces + (implemented_by_cls,)
  125. @staticmethod
  126. def _argument_names_for_repr(interfaces):
  127. # These don't actually have to be interfaces, they could be other
  128. # Specification objects like Implements. Also, the first
  129. # one is typically/nominally the cls.
  130. ordered_names = []
  131. names = set()
  132. for iface in interfaces:
  133. duplicate_transform = repr
  134. if isinstance(iface, InterfaceClass):
  135. # Special case to get 'foo.bar.IFace'
  136. # instead of '<InterfaceClass foo.bar.IFace>'
  137. this_name = iface.__name__
  138. duplicate_transform = str
  139. elif isinstance(iface, type):
  140. # Likewise for types. (Ignoring legacy old-style
  141. # classes.)
  142. this_name = iface.__name__
  143. duplicate_transform = _implements_name
  144. elif (
  145. isinstance(iface, Implements) and
  146. not iface.declared and
  147. iface.inherit in interfaces
  148. ):
  149. # If nothing is declared, there's no need to even print this;
  150. # it would just show as ``classImplements(Class)``, and the
  151. # ``Class`` has typically already.
  152. continue
  153. else:
  154. this_name = repr(iface)
  155. already_seen = this_name in names
  156. names.add(this_name)
  157. if already_seen:
  158. this_name = duplicate_transform(iface)
  159. ordered_names.append(this_name)
  160. return ', '.join(ordered_names)
  161. class _ImmutableDeclaration(Declaration):
  162. # A Declaration that is immutable. Used as a singleton to
  163. # return empty answers for things like ``implementedBy``.
  164. # We have to define the actual singleton after normalizeargs
  165. # is defined, and that in turn is defined after InterfaceClass and
  166. # Implements.
  167. __slots__ = ()
  168. __instance = None
  169. def __new__(cls):
  170. if _ImmutableDeclaration.__instance is None:
  171. _ImmutableDeclaration.__instance = object.__new__(cls)
  172. return _ImmutableDeclaration.__instance
  173. def __reduce__(self):
  174. return "_empty"
  175. @property
  176. def __bases__(self):
  177. return ()
  178. @__bases__.setter
  179. def __bases__(self, new_bases):
  180. # We expect the superclass constructor to set ``self.__bases__ = ()``.
  181. # Rather than attempt to special case that in the constructor and
  182. # allow setting __bases__ only at that time, it's easier to just allow
  183. # setting the empty tuple at any time. That makes ``x.__bases__ =
  184. # x.__bases__`` a nice no-op too. (Skipping the superclass constructor
  185. # altogether is a recipe for maintenance headaches.)
  186. if new_bases != ():
  187. raise TypeError(
  188. "Cannot set non-empty bases on shared empty Declaration."
  189. )
  190. # As the immutable empty declaration, we cannot be changed.
  191. # This means there's no logical reason for us to have dependents
  192. # or subscriptions: we'll never notify them. So there's no need for
  193. # us to keep track of any of that.
  194. @property
  195. def dependents(self):
  196. return {}
  197. changed = subscribe = unsubscribe = lambda self, _ignored: None
  198. def interfaces(self):
  199. # An empty iterator
  200. return iter(())
  201. def extends(self, interface, strict=True):
  202. return interface is self._ROOT
  203. def get(self, name, default=None):
  204. return default
  205. def weakref(self, callback=None):
  206. # We're a singleton, we never go away. So there's no need to return
  207. # distinct weakref objects here; their callbacks will never be called.
  208. # Instead, we only need to return a callable that returns ourself. The
  209. # easiest one is to return _ImmutableDeclaration itself; testing on
  210. # Python 3.8 shows that's faster than a function that returns _empty.
  211. # (Remember, one goal is to avoid allocating any object, and that
  212. # includes a method.)
  213. return _ImmutableDeclaration
  214. @property
  215. def _v_attrs(self):
  216. # _v_attrs is not a public, documented property, but some client code
  217. # uses it anyway as a convenient place to cache things. To keep the
  218. # empty declaration truly immutable, we must ignore that. That
  219. # includes ignoring assignments as well.
  220. return {}
  221. @_v_attrs.setter
  222. def _v_attrs(self, new_attrs):
  223. pass
  224. ##############################################################################
  225. #
  226. # Implementation specifications
  227. #
  228. # These specify interfaces implemented by instances of classes
  229. class Implements(NameAndModuleComparisonMixin,
  230. Declaration):
  231. # Inherit from NameAndModuleComparisonMixin to be mutually comparable with
  232. # InterfaceClass objects. (The two must be mutually comparable to be able
  233. # to work in e.g., BTrees.) Instances of this class generally don't have a
  234. # __module__ other than `zope.interface.declarations`, whereas they *do*
  235. # have a __name__ that is the fully qualified name of the object they are
  236. # representing.
  237. # Note, though, that equality and hashing are still identity based. This
  238. # accounts for things like nested objects that have the same name
  239. # (typically only in tests) and is consistent with pickling. As far as
  240. # comparisons to InterfaceClass goes, we'll never have equal name and
  241. # module to those, so we're still consistent there. Instances of this
  242. # class are essentially intended to be unique and are heavily cached (note
  243. # how our __reduce__ handles this) so having identity based hash and eq
  244. # should also work.
  245. # We want equality and hashing to be based on identity. However, we can't
  246. # actually implement __eq__/__ne__ to do this because sometimes we get
  247. # wrapped in a proxy. We need to let the proxy types implement these
  248. # methods so they can handle unwrapping and then rely on: (1) the
  249. # interpreter automatically changing `implements == proxy` into `proxy ==
  250. # implements` (which will call proxy.__eq__ to do the unwrapping) and then
  251. # (2) the default equality and hashing semantics being identity based.
  252. # class whose specification should be used as additional base
  253. inherit = None
  254. # interfaces actually declared for a class
  255. declared = ()
  256. # Weak cache of {class: <implements>} for super objects.
  257. # Created on demand. These are rare, as of 5.0 anyway. Using a class
  258. # level default doesn't take space in instances. Using _v_attrs would be
  259. # another place to store this without taking space unless needed.
  260. _super_cache = None
  261. __name__ = '?'
  262. @classmethod
  263. def named(cls, name, *bases):
  264. # Implementation method: Produce an Implements interface with a fully
  265. # fleshed out __name__ before calling the constructor, which sets
  266. # bases to the given interfaces and which may pass this object to
  267. # other objects (e.g., to adjust dependents). If they're sorting or
  268. # comparing by name, this needs to be set.
  269. inst = cls.__new__(cls)
  270. inst.__name__ = name
  271. inst.__init__(*bases)
  272. return inst
  273. def changed(self, originally_changed):
  274. try:
  275. del self._super_cache
  276. except AttributeError:
  277. pass
  278. return super().changed(originally_changed)
  279. def __repr__(self):
  280. if self.inherit:
  281. name = (
  282. getattr(self.inherit, '__name__', None) or
  283. _implements_name(self.inherit)
  284. )
  285. else:
  286. name = self.__name__
  287. declared_names = self._argument_names_for_repr(self.declared)
  288. if declared_names:
  289. declared_names = ', ' + declared_names
  290. return f'classImplements({name}{declared_names})'
  291. def __reduce__(self):
  292. return implementedBy, (self.inherit, )
  293. def _implements_name(ob):
  294. # Return the __name__ attribute to be used by its __implemented__
  295. # property.
  296. # This must be stable for the "same" object across processes
  297. # because it is used for sorting. It needn't be unique, though, in cases
  298. # like nested classes named Foo created by different functions, because
  299. # equality and hashing is still based on identity.
  300. # It might be nice to use __qualname__ on Python 3, but that would produce
  301. # different values between Py2 and Py3.
  302. # Special-case 'InterfaceBase': its '__module__' member descriptor
  303. # behaves differently across Python 3.x versions.
  304. if ob is InterfaceBase:
  305. return 'zope.interface.interface.InterfaceBase'
  306. return (getattr(ob, '__module__', '?') or '?') + \
  307. '.' + (getattr(ob, '__name__', '?') or '?')
  308. def _implementedBy_super(sup):
  309. # TODO: This is now simple enough we could probably implement
  310. # in C if needed.
  311. # If the class MRO is strictly linear, we could just
  312. # follow the normal algorithm for the next class in the
  313. # search order (e.g., just return
  314. # ``implemented_by_next``). But when diamond inheritance
  315. # or mixins + interface declarations are present, we have
  316. # to consider the whole MRO and compute a new Implements
  317. # that excludes the classes being skipped over but
  318. # includes everything else.
  319. implemented_by_self = implementedBy(sup.__self_class__)
  320. cache = implemented_by_self._super_cache # pylint:disable=protected-access
  321. if cache is None:
  322. cache = implemented_by_self._super_cache = weakref.WeakKeyDictionary()
  323. key = sup.__thisclass__
  324. try:
  325. return cache[key]
  326. except KeyError:
  327. pass
  328. next_cls = _next_super_class(sup)
  329. # For ``implementedBy(cls)``:
  330. # .__bases__ is .declared + [implementedBy(b) for b in cls.__bases__]
  331. # .inherit is cls
  332. implemented_by_next = implementedBy(next_cls)
  333. mro = sup.__self_class__.__mro__
  334. ix_next_cls = mro.index(next_cls)
  335. classes_to_keep = mro[ix_next_cls:]
  336. new_bases = [implementedBy(c) for c in classes_to_keep]
  337. new = Implements.named(
  338. implemented_by_self.__name__ + ':' + implemented_by_next.__name__,
  339. *new_bases
  340. )
  341. new.inherit = implemented_by_next.inherit
  342. new.declared = implemented_by_next.declared
  343. # I don't *think* that new needs to subscribe to ``implemented_by_self``;
  344. # it auto-subscribed to its bases, and that should be good enough.
  345. cache[key] = new
  346. return new
  347. @_use_c_impl
  348. def implementedBy(
  349. cls
  350. ): # pylint:disable=too-many-return-statements,too-many-branches
  351. """Return the interfaces implemented for a class' instances
  352. The value returned is an `~zope.interface.interfaces.IDeclaration`.
  353. """
  354. try:
  355. if isinstance(cls, super):
  356. # Yes, this needs to be inside the try: block. Some objects
  357. # like security proxies even break isinstance.
  358. return _implementedBy_super(cls)
  359. spec = cls.__dict__.get('__implemented__')
  360. except AttributeError:
  361. # we can't get the class dict. This is probably due to a
  362. # security proxy. If this is the case, then probably no
  363. # descriptor was installed for the class.
  364. # We don't want to depend directly on zope.security in
  365. # zope.interface, but we'll try to make reasonable
  366. # accommodations in an indirect way.
  367. # We'll check to see if there's an implements:
  368. spec = getattr(cls, '__implemented__', None)
  369. if spec is None:
  370. # There's no spec stred in the class. Maybe its a builtin:
  371. spec = BuiltinImplementationSpecifications.get(cls)
  372. if spec is not None:
  373. return spec
  374. return _empty
  375. if spec.__class__ == Implements:
  376. # we defaulted to _empty or there was a spec. Good enough.
  377. # Return it.
  378. return spec
  379. # TODO: need old style __implements__ compatibility?
  380. # Hm, there's an __implemented__, but it's not a spec. Must be
  381. # an old-style declaration. Just compute a spec for it
  382. return Declaration(*_normalizeargs((spec, )))
  383. if isinstance(spec, Implements):
  384. return spec
  385. if spec is None:
  386. spec = BuiltinImplementationSpecifications.get(cls)
  387. if spec is not None:
  388. return spec
  389. # TODO: need old style __implements__ compatibility?
  390. spec_name = _implements_name(cls)
  391. if spec is not None:
  392. # old-style __implemented__ = foo declaration
  393. spec = (spec, ) # tuplefy, as it might be just an int
  394. spec = Implements.named(spec_name, *_normalizeargs(spec))
  395. spec.inherit = None # old-style implies no inherit
  396. del cls.__implemented__ # get rid of the old-style declaration
  397. else:
  398. try:
  399. bases = cls.__bases__
  400. except AttributeError:
  401. if not callable(cls):
  402. raise TypeError("ImplementedBy called for non-factory", cls)
  403. bases = ()
  404. spec = Implements.named(spec_name, *[implementedBy(c) for c in bases])
  405. spec.inherit = cls
  406. try:
  407. cls.__implemented__ = spec
  408. if not hasattr(cls, '__providedBy__'):
  409. cls.__providedBy__ = objectSpecificationDescriptor
  410. if isinstance(cls, type) and '__provides__' not in cls.__dict__:
  411. # Make sure we get a __provides__ descriptor
  412. cls.__provides__ = ClassProvides(
  413. cls, getattr(cls, '__class__', type(cls)),
  414. )
  415. except TypeError:
  416. if not isinstance(cls, type):
  417. raise TypeError("ImplementedBy called for non-type", cls)
  418. BuiltinImplementationSpecifications[cls] = spec
  419. return spec
  420. def classImplementsOnly(cls, *interfaces):
  421. """
  422. Declare the only interfaces implemented by instances of a class
  423. The arguments after the class are one or more interfaces or interface
  424. specifications (`~zope.interface.interfaces.IDeclaration` objects).
  425. The interfaces given (including the interfaces in the specifications)
  426. replace any previous declarations, *including* inherited definitions. If
  427. you wish to preserve inherited declarations, you can pass
  428. ``implementedBy(cls)`` in *interfaces*. This can be used to alter the
  429. interface resolution order.
  430. """
  431. spec = implementedBy(cls)
  432. # Clear out everything inherited. It's important to
  433. # also clear the bases right now so that we don't improperly discard
  434. # interfaces that are already implemented by *old* bases that we're
  435. # about to get rid of.
  436. spec.declared = ()
  437. spec.inherit = None
  438. spec.__bases__ = ()
  439. _classImplements_ordered(spec, interfaces, ())
  440. def classImplements(cls, *interfaces):
  441. """
  442. Declare additional interfaces implemented for instances of a class
  443. The arguments after the class are one or more interfaces or interface
  444. specifications (`~zope.interface.interfaces.IDeclaration` objects).
  445. The interfaces given (including the interfaces in the specifications)
  446. are added to any interfaces previously declared. An effort is made to
  447. keep a consistent C3 resolution order, but this cannot be guaranteed.
  448. .. versionchanged:: 5.0.0
  449. Each individual interface in *interfaces* may be added to either the
  450. beginning or end of the list of interfaces declared for *cls*,
  451. based on inheritance, in order to try to maintain a consistent
  452. resolution order. Previously, all interfaces were added to the end.
  453. .. versionchanged:: 5.1.0
  454. If *cls* is already declared to implement an interface (or derived
  455. interface) in *interfaces* through inheritance, the interface is
  456. ignored. Previously, it would redundantly be made direct base of *cls*,
  457. which often produced inconsistent interface resolution orders. Now, the
  458. order will be consistent, but may change. Also, if the ``__bases__``
  459. of the *cls* are later changed, the *cls* will no longer be considered
  460. to implement such an interface (changing the ``__bases__`` of *cls* has
  461. never been supported).
  462. """
  463. spec = implementedBy(cls)
  464. interfaces = tuple(_normalizeargs(interfaces))
  465. before = []
  466. after = []
  467. # Take steps to try to avoid producing an invalid resolution
  468. # order, while still allowing for BWC (in the past, we always
  469. # appended)
  470. for iface in interfaces:
  471. for b in spec.declared:
  472. if iface.extends(b):
  473. before.append(iface)
  474. break
  475. else:
  476. after.append(iface)
  477. _classImplements_ordered(spec, tuple(before), tuple(after))
  478. def classImplementsFirst(cls, iface):
  479. """
  480. Declare that instances of *cls* additionally provide *iface*.
  481. The second argument is an interface or interface specification.
  482. It is added as the highest priority (first in the IRO) interface;
  483. no attempt is made to keep a consistent resolution order.
  484. .. versionadded:: 5.0.0
  485. """
  486. spec = implementedBy(cls)
  487. _classImplements_ordered(spec, (iface,), ())
  488. def _classImplements_ordered(spec, before=(), after=()):
  489. # Elide everything already inherited.
  490. # Except, if it is the root, and we don't already declare anything else
  491. # that would imply it, allow the root through. (TODO: When we disallow
  492. # non-strict IRO, this part of the check can be removed because it's not
  493. # possible to re-declare like that.)
  494. before = [
  495. x
  496. for x in before
  497. if not spec.isOrExtends(x) or (x is Interface and not spec.declared)
  498. ]
  499. after = [
  500. x
  501. for x in after
  502. if not spec.isOrExtends(x) or (x is Interface and not spec.declared)
  503. ]
  504. # eliminate duplicates
  505. new_declared = []
  506. seen = set()
  507. for lst in before, spec.declared, after:
  508. for b in lst:
  509. if b not in seen:
  510. new_declared.append(b)
  511. seen.add(b)
  512. spec.declared = tuple(new_declared)
  513. # compute the bases
  514. bases = new_declared # guaranteed no dupes
  515. if spec.inherit is not None:
  516. for c in spec.inherit.__bases__:
  517. b = implementedBy(c)
  518. if b not in seen:
  519. seen.add(b)
  520. bases.append(b)
  521. spec.__bases__ = tuple(bases)
  522. def _implements_advice(cls):
  523. interfaces, do_classImplements = cls.__dict__['__implements_advice_data__']
  524. del cls.__implements_advice_data__
  525. do_classImplements(cls, *interfaces)
  526. return cls
  527. class implementer:
  528. """
  529. Declare the interfaces implemented by instances of a class.
  530. This function is called as a class decorator.
  531. The arguments are one or more interfaces or interface specifications
  532. (`~zope.interface.interfaces.IDeclaration` objects).
  533. The interfaces given (including the interfaces in the specifications) are
  534. added to any interfaces previously declared, unless the interface is
  535. already implemented.
  536. Previous declarations include declarations for base classes unless
  537. implementsOnly was used.
  538. This function is provided for convenience. It provides a more convenient
  539. way to call `classImplements`. For example::
  540. @implementer(I1)
  541. class C(object):
  542. pass
  543. is equivalent to calling::
  544. classImplements(C, I1)
  545. after the class has been created.
  546. .. seealso:: `classImplements`
  547. The change history provided there applies to this function too.
  548. """
  549. __slots__ = ('interfaces',)
  550. def __init__(self, *interfaces):
  551. self.interfaces = interfaces
  552. def __call__(self, ob):
  553. if isinstance(ob, type):
  554. # This is the common branch for classes.
  555. classImplements(ob, *self.interfaces)
  556. return ob
  557. spec_name = _implements_name(ob)
  558. spec = Implements.named(spec_name, *self.interfaces)
  559. try:
  560. ob.__implemented__ = spec
  561. except AttributeError:
  562. raise TypeError("Can't declare implements", ob)
  563. return ob
  564. class implementer_only:
  565. """Declare the only interfaces implemented by instances of a class
  566. This function is called as a class decorator.
  567. The arguments are one or more interfaces or interface
  568. specifications (`~zope.interface.interfaces.IDeclaration` objects).
  569. Previous declarations including declarations for base classes
  570. are overridden.
  571. This function is provided for convenience. It provides a more
  572. convenient way to call `classImplementsOnly`. For example::
  573. @implementer_only(I1)
  574. class C(object): pass
  575. is equivalent to calling::
  576. classImplementsOnly(I1)
  577. after the class has been created.
  578. """
  579. def __init__(self, *interfaces):
  580. self.interfaces = interfaces
  581. def __call__(self, ob):
  582. if isinstance(ob, (FunctionType, MethodType)):
  583. # XXX Does this decorator make sense for anything but classes?
  584. # I don't think so. There can be no inheritance of interfaces
  585. # on a method or function....
  586. raise ValueError('The implementer_only decorator is not '
  587. 'supported for methods or functions.')
  588. # Assume it's a class:
  589. classImplementsOnly(ob, *self.interfaces)
  590. return ob
  591. ##############################################################################
  592. #
  593. # Instance declarations
  594. class Provides(Declaration): # Really named ProvidesClass
  595. """Implement ``__provides__``, the instance-specific specification
  596. When an object is pickled, we pickle the interfaces that it implements.
  597. """
  598. def __init__(self, cls, *interfaces):
  599. self.__args = (cls, ) + interfaces
  600. self._cls = cls
  601. Declaration.__init__(
  602. self, *self._add_interfaces_to_cls(interfaces, cls)
  603. )
  604. # Added to by ``moduleProvides``, et al
  605. _v_module_names = ()
  606. def __repr__(self):
  607. # The typical way to create instances of this object is via calling
  608. # ``directlyProvides(...)`` or ``alsoProvides()``, but that's not the
  609. # only way. Proxies, for example, directly use the ``Provides(...)``
  610. # function (which is the more generic method, and what we pickle as).
  611. # We're after the most readable, useful repr in the common case, so we
  612. # use the most common name.
  613. #
  614. # We also cooperate with ``moduleProvides`` to attempt to do the right
  615. # thing for that API. See it for details.
  616. function_name = 'directlyProvides'
  617. if self._cls is ModuleType and self._v_module_names:
  618. # See notes in ``moduleProvides``/``directlyProvides``
  619. providing_on_module = True
  620. interfaces = self.__args[1:]
  621. else:
  622. providing_on_module = False
  623. interfaces = (self._cls,) + self.__bases__
  624. ordered_names = self._argument_names_for_repr(interfaces)
  625. if providing_on_module:
  626. mod_names = self._v_module_names
  627. if len(mod_names) == 1:
  628. mod_names = "sys.modules[%r]" % mod_names[0]
  629. ordered_names = (
  630. f'{mod_names}, '
  631. ) + ordered_names
  632. return "{}({})".format(
  633. function_name,
  634. ordered_names,
  635. )
  636. def __reduce__(self):
  637. # This reduces to the Provides *function*, not
  638. # this class.
  639. return Provides, self.__args
  640. __module__ = 'zope.interface'
  641. def __get__(self, inst, cls):
  642. """Make sure that a class __provides__ doesn't leak to an instance
  643. """
  644. if inst is None and cls is self._cls:
  645. # We were accessed through a class, so we are the class'
  646. # provides spec. Just return this object, but only if we are
  647. # being called on the same class that we were defined for:
  648. return self
  649. raise AttributeError('__provides__')
  650. ProvidesClass = Provides
  651. # Registry of instance declarations
  652. # This is a memory optimization to allow objects to share specifications.
  653. InstanceDeclarations = weakref.WeakValueDictionary()
  654. def Provides(*interfaces): # pylint:disable=function-redefined
  655. """Declaration for an instance of *cls*.
  656. The correct signature is ``cls, *interfaces``.
  657. The *cls* is necessary to avoid the
  658. construction of inconsistent resolution orders.
  659. Instance declarations are shared among instances that have the same
  660. declaration. The declarations are cached in a weak value dictionary.
  661. """
  662. spec = InstanceDeclarations.get(interfaces)
  663. if spec is None:
  664. spec = ProvidesClass(*interfaces)
  665. InstanceDeclarations[interfaces] = spec
  666. return spec
  667. Provides.__safe_for_unpickling__ = True
  668. def directlyProvides(object, *interfaces): # pylint:disable=redefined-builtin
  669. """Declare interfaces declared directly for an object
  670. The arguments after the object are one or more interfaces or interface
  671. specifications (`~zope.interface.interfaces.IDeclaration` objects).
  672. The interfaces given (including the interfaces in the specifications)
  673. replace interfaces previously declared for the object.
  674. """
  675. cls = getattr(object, '__class__', None)
  676. if cls is not None and getattr(cls, '__class__', None) is cls:
  677. # It's a meta class (well, at least it it could be an extension class)
  678. # Note that we can't get here from the tests: there is no normal
  679. # class which isn't descriptor aware.
  680. if not isinstance(object, type):
  681. raise TypeError("Attempt to make an interface declaration on a "
  682. "non-descriptor-aware class")
  683. interfaces = _normalizeargs(interfaces)
  684. if cls is None:
  685. cls = type(object)
  686. if issubclass(cls, type):
  687. # we have a class or type. We'll use a special descriptor
  688. # that provides some extra caching
  689. object.__provides__ = ClassProvides(object, cls, *interfaces)
  690. else:
  691. provides = object.__provides__ = Provides(cls, *interfaces)
  692. # See notes in ``moduleProvides``.
  693. if issubclass(cls, ModuleType) and hasattr(object, '__name__'):
  694. provides._v_module_names += (object.__name__,)
  695. def alsoProvides(object, *interfaces): # pylint:disable=redefined-builtin
  696. """Declare interfaces declared directly for an object
  697. The arguments after the object are one or more interfaces or interface
  698. specifications (`~zope.interface.interfaces.IDeclaration` objects).
  699. The interfaces given (including the interfaces in the specifications) are
  700. added to the interfaces previously declared for the object.
  701. """
  702. directlyProvides(object, directlyProvidedBy(object), *interfaces)
  703. def noLongerProvides(object, interface): # pylint:disable=redefined-builtin
  704. """ Removes a directly provided interface from an object.
  705. """
  706. directlyProvides(object, directlyProvidedBy(object) - interface)
  707. if interface.providedBy(object):
  708. raise ValueError("Can only remove directly provided interfaces.")
  709. @_use_c_impl
  710. class ClassProvidesBase(SpecificationBase):
  711. __slots__ = (
  712. '_cls',
  713. '_implements',
  714. )
  715. def __get__(self, inst, cls):
  716. # member slots are set by subclass
  717. # pylint:disable=no-member
  718. if cls is self._cls:
  719. # We only work if called on the class we were defined for
  720. if inst is None:
  721. # We were accessed through a class, so we are the class'
  722. # provides spec. Just return this object as is:
  723. return self
  724. return self._implements
  725. raise AttributeError('__provides__')
  726. class ClassProvides(Declaration, ClassProvidesBase):
  727. """Special descriptor for class ``__provides__``
  728. The descriptor caches the implementedBy info, so that
  729. we can get declarations for objects without instance-specific
  730. interfaces a bit quicker.
  731. """
  732. __slots__ = (
  733. '__args',
  734. )
  735. def __init__(self, cls, metacls, *interfaces):
  736. self._cls = cls
  737. self._implements = implementedBy(cls)
  738. self.__args = (cls, metacls, ) + interfaces
  739. Declaration.__init__(
  740. self, *self._add_interfaces_to_cls(interfaces, metacls)
  741. )
  742. def __repr__(self):
  743. # There are two common ways to get instances of this object: The most
  744. # interesting way is calling ``@provider(..)`` as a decorator of a
  745. # class; this is the same as calling ``directlyProvides(cls, ...)``.
  746. #
  747. # The other way is by default: anything that invokes
  748. # ``implementedBy(x)`` will wind up putting an instance in
  749. # ``type(x).__provides__``; this includes the ``@implementer(...)``
  750. # decorator. Those instances won't have any interfaces.
  751. #
  752. # Thus, as our repr, we go with the ``directlyProvides()`` syntax.
  753. interfaces = (self._cls, ) + self.__args[2:]
  754. ordered_names = self._argument_names_for_repr(interfaces)
  755. return f"directlyProvides({ordered_names})"
  756. def __reduce__(self):
  757. return self.__class__, self.__args
  758. # Copy base-class method for speed
  759. __get__ = ClassProvidesBase.__get__
  760. # autopep8: off (it breaks the statements in the "if")
  761. def directlyProvidedBy(object): # pylint:disable=redefined-builtin
  762. """Return the interfaces directly provided by the given object
  763. The value returned is an `~zope.interface.interfaces.IDeclaration`.
  764. """
  765. provides = getattr(object, "__provides__", None)
  766. if (
  767. provides is None # no spec
  768. # We might have gotten the implements spec, as an
  769. # optimization. If so, it's like having only one base, that we
  770. # lop off to exclude class-supplied declarations:
  771. or isinstance(provides, Implements) # noqa W503
  772. ):
  773. return _empty
  774. # Strip off the class part of the spec:
  775. return Declaration(provides.__bases__[:-1])
  776. # autopep8: on
  777. class provider:
  778. """Declare interfaces provided directly by a class
  779. This function is called in a class definition.
  780. The arguments are one or more interfaces or interface specifications
  781. (`~zope.interface.interfaces.IDeclaration` objects).
  782. The given interfaces (including the interfaces in the specifications)
  783. are used to create the class's direct-object interface specification.
  784. An error will be raised if the module class has an direct interface
  785. specification. In other words, it is an error to call this function more
  786. than once in a class definition.
  787. Note that the given interfaces have nothing to do with the interfaces
  788. implemented by instances of the class.
  789. This function is provided for convenience. It provides a more convenient
  790. way to call `directlyProvides` for a class. For example::
  791. @provider(I1)
  792. class C:
  793. pass
  794. is equivalent to calling::
  795. directlyProvides(C, I1)
  796. after the class has been created.
  797. """
  798. def __init__(self, *interfaces):
  799. self.interfaces = interfaces
  800. def __call__(self, ob):
  801. directlyProvides(ob, *self.interfaces)
  802. return ob
  803. def moduleProvides(*interfaces):
  804. """Declare interfaces provided by a module
  805. This function is used in a module definition.
  806. The arguments are one or more interfaces or interface specifications
  807. (`~zope.interface.interfaces.IDeclaration` objects).
  808. The given interfaces (including the interfaces in the specifications) are
  809. used to create the module's direct-object interface specification. An
  810. error will be raised if the module already has an interface specification.
  811. In other words, it is an error to call this function more than once in a
  812. module definition.
  813. This function is provided for convenience. It provides a more convenient
  814. way to call directlyProvides. For example::
  815. moduleProvides(I1)
  816. is equivalent to::
  817. directlyProvides(sys.modules[__name__], I1)
  818. """
  819. frame = sys._getframe(1) # pylint:disable=protected-access
  820. locals = frame.f_locals # pylint:disable=redefined-builtin
  821. # Try to make sure we were called from a module body
  822. if (locals is not frame.f_globals) or ('__name__' not in locals):
  823. raise TypeError(
  824. "moduleProvides can only be used from a module definition.")
  825. if '__provides__' in locals:
  826. raise TypeError(
  827. "moduleProvides can only be used once in a module definition.")
  828. # Note: This is cached based on the key ``(ModuleType, *interfaces)``; One
  829. # consequence is that any module that provides the same interfaces gets
  830. # the same ``__repr__``, meaning that you can't tell what module such a
  831. # declaration came from. Adding the module name to ``_v_module_names``
  832. # attempts to correct for this; it works in some common situations, but
  833. # fails (1) after pickling (the data is lost) and (2) if declarations are
  834. # actually shared and (3) if the alternate spelling of
  835. # ``directlyProvides()`` is used. Problem (3) is fixed by cooperating
  836. # with ``directlyProvides`` to maintain this information, and problem (2)
  837. # is worked around by printing all the names, but (1) is unsolvable
  838. # without introducing new classes or changing the stored data...but it
  839. # doesn't actually matter, because ``ModuleType`` can't be pickled!
  840. p = locals["__provides__"] = Provides(ModuleType,
  841. *_normalizeargs(interfaces))
  842. p._v_module_names += (locals['__name__'],)
  843. ##############################################################################
  844. #
  845. # Declaration querying support
  846. # XXX: is this a fossil? Nobody calls it, no unit tests exercise it, no
  847. # doctests import it, and the package __init__ doesn't import it.
  848. # (Answer: Versions of zope.container prior to 4.4.0 called this,
  849. # and zope.proxy.decorator up through at least 4.3.5 called this.)
  850. def ObjectSpecification(direct, cls):
  851. """Provide object specifications
  852. These combine information for the object and for it's classes.
  853. """
  854. return Provides(cls, direct) # pragma: no cover fossil
  855. @_use_c_impl
  856. def getObjectSpecification(ob):
  857. try:
  858. provides = ob.__provides__
  859. except AttributeError:
  860. provides = None
  861. if provides is not None:
  862. if isinstance(provides, SpecificationBase):
  863. return provides
  864. try:
  865. cls = ob.__class__
  866. except AttributeError:
  867. # We can't get the class, so just consider provides
  868. return _empty
  869. return implementedBy(cls)
  870. @_use_c_impl
  871. def providedBy(ob):
  872. """
  873. Return the interfaces provided by *ob*.
  874. If *ob* is a :class:`super` object, then only interfaces implemented
  875. by the remainder of the classes in the method resolution order are
  876. considered. Interfaces directly provided by the object underlying *ob*
  877. are not.
  878. """
  879. # Here we have either a special object, an old-style declaration
  880. # or a descriptor
  881. # Try to get __providedBy__
  882. try:
  883. if isinstance(ob, super): # Some objects raise errors on isinstance()
  884. return implementedBy(ob)
  885. r = ob.__providedBy__
  886. except AttributeError:
  887. # Not set yet. Fall back to lower-level thing that computes it
  888. return getObjectSpecification(ob)
  889. try:
  890. # We might have gotten a descriptor from an instance of a
  891. # class (like an ExtensionClass) that doesn't support
  892. # descriptors. We'll make sure we got one by trying to get
  893. # the only attribute, which all specs have.
  894. r.extends
  895. except AttributeError:
  896. # The object's class doesn't understand descriptors.
  897. # Sigh. We need to get an object descriptor, but we have to be
  898. # careful. We want to use the instance's __provides__, if
  899. # there is one, but only if it didn't come from the class.
  900. try:
  901. r = ob.__provides__
  902. except AttributeError:
  903. # No __provides__, so just fall back to implementedBy
  904. return implementedBy(ob.__class__)
  905. # We need to make sure we got the __provides__ from the
  906. # instance. We'll do this by making sure we don't get the same
  907. # thing from the class:
  908. try:
  909. cp = ob.__class__.__provides__
  910. except AttributeError:
  911. # The ob doesn't have a class or the class has no
  912. # provides, assume we're done:
  913. return r
  914. if r is cp:
  915. # Oops, we got the provides from the class. This means
  916. # the object doesn't have it's own. We should use implementedBy
  917. return implementedBy(ob.__class__)
  918. return r
  919. @_use_c_impl
  920. class ObjectSpecificationDescriptor:
  921. """Implement the ``__providedBy__`` attribute
  922. The ``__providedBy__`` attribute computes the interfaces provided by an
  923. object. If an object has an ``__provides__`` attribute, that is returned.
  924. Otherwise, `implementedBy` the *cls* is returned.
  925. .. versionchanged:: 5.4.0
  926. Both the default (C) implementation and the Python implementation
  927. now let exceptions raised by accessing ``__provides__`` propagate.
  928. Previously, the C version ignored all exceptions.
  929. .. versionchanged:: 5.4.0
  930. The Python implementation now matches the C implementation and lets
  931. a ``__provides__`` of ``None`` override what the class is declared to
  932. implement.
  933. """
  934. def __get__(self, inst, cls):
  935. """Get an object specification for an object
  936. """
  937. if inst is None:
  938. return getObjectSpecification(cls)
  939. try:
  940. return inst.__provides__
  941. except AttributeError:
  942. return implementedBy(cls)
  943. ##############################################################################
  944. def _normalizeargs(sequence, output=None):
  945. """Normalize declaration arguments
  946. Normalization arguments might contain Declarions, tuples, or single
  947. interfaces.
  948. Anything but individual interfaces or implements specs will be expanded.
  949. """
  950. if output is None:
  951. output = []
  952. cls = sequence.__class__
  953. if InterfaceClass in cls.__mro__ or Implements in cls.__mro__:
  954. output.append(sequence)
  955. else:
  956. for v in sequence:
  957. _normalizeargs(v, output)
  958. return output
  959. _empty = _ImmutableDeclaration()
  960. objectSpecificationDescriptor = ObjectSpecificationDescriptor()