declarations.py 47 KB

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