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

declarations.py 42KB

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