interface.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. ##############################################################################
  2. #
  3. # Copyright (c) 2001, 2002 Zope Foundation and Contributors.
  4. # All Rights Reserved.
  5. #
  6. # This software is subject to the provisions of the Zope Public License,
  7. # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
  8. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
  9. # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  10. # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
  11. # FOR A PARTICULAR PURPOSE.
  12. #
  13. ##############################################################################
  14. """Interface object implementation
  15. """
  16. # pylint:disable=protected-access
  17. import sys
  18. from types import MethodType
  19. from types import FunctionType
  20. import weakref
  21. from zope.interface._compat import _use_c_impl
  22. from zope.interface._compat import PYTHON2 as PY2
  23. from zope.interface.exceptions import Invalid
  24. from zope.interface.ro import ro as calculate_ro
  25. from zope.interface import ro
  26. __all__ = [
  27. # Most of the public API from this module is directly exported
  28. # from zope.interface. The only remaining public API intended to
  29. # be imported from here should be those few things documented as
  30. # such.
  31. 'InterfaceClass',
  32. 'Specification',
  33. 'adapter_hooks',
  34. ]
  35. CO_VARARGS = 4
  36. CO_VARKEYWORDS = 8
  37. # Put in the attrs dict of an interface by ``taggedValue`` and ``invariants``
  38. TAGGED_DATA = '__interface_tagged_values__'
  39. # Put in the attrs dict of an interface by ``interfacemethod``
  40. INTERFACE_METHODS = '__interface_methods__'
  41. _decorator_non_return = object()
  42. _marker = object()
  43. def invariant(call):
  44. f_locals = sys._getframe(1).f_locals
  45. tags = f_locals.setdefault(TAGGED_DATA, {})
  46. invariants = tags.setdefault('invariants', [])
  47. invariants.append(call)
  48. return _decorator_non_return
  49. def taggedValue(key, value):
  50. """Attaches a tagged value to an interface at definition time."""
  51. f_locals = sys._getframe(1).f_locals
  52. tagged_values = f_locals.setdefault(TAGGED_DATA, {})
  53. tagged_values[key] = value
  54. return _decorator_non_return
  55. class Element(object):
  56. """
  57. Default implementation of `zope.interface.interfaces.IElement`.
  58. """
  59. # We can't say this yet because we don't have enough
  60. # infrastructure in place.
  61. #
  62. #implements(IElement)
  63. def __init__(self, __name__, __doc__=''): # pylint:disable=redefined-builtin
  64. if not __doc__ and __name__.find(' ') >= 0:
  65. __doc__ = __name__
  66. __name__ = None
  67. self.__name__ = __name__
  68. self.__doc__ = __doc__
  69. # Tagged values are rare, especially on methods or attributes.
  70. # Deferring the allocation can save substantial memory.
  71. self.__tagged_values = None
  72. def getName(self):
  73. """ Returns the name of the object. """
  74. return self.__name__
  75. def getDoc(self):
  76. """ Returns the documentation for the object. """
  77. return self.__doc__
  78. ###
  79. # Tagged values.
  80. #
  81. # Direct tagged values are set only in this instance. Others
  82. # may be inherited (for those subclasses that have that concept).
  83. ###
  84. def getTaggedValue(self, tag):
  85. """ Returns the value associated with 'tag'. """
  86. if not self.__tagged_values:
  87. raise KeyError(tag)
  88. return self.__tagged_values[tag]
  89. def queryTaggedValue(self, tag, default=None):
  90. """ Returns the value associated with 'tag'. """
  91. return self.__tagged_values.get(tag, default) if self.__tagged_values else default
  92. def getTaggedValueTags(self):
  93. """ Returns a collection of all tags. """
  94. return self.__tagged_values.keys() if self.__tagged_values else ()
  95. def setTaggedValue(self, tag, value):
  96. """ Associates 'value' with 'key'. """
  97. if self.__tagged_values is None:
  98. self.__tagged_values = {}
  99. self.__tagged_values[tag] = value
  100. queryDirectTaggedValue = queryTaggedValue
  101. getDirectTaggedValue = getTaggedValue
  102. getDirectTaggedValueTags = getTaggedValueTags
  103. SpecificationBasePy = object # filled by _use_c_impl.
  104. @_use_c_impl
  105. class SpecificationBase(object):
  106. # This object is the base of the inheritance hierarchy for ClassProvides:
  107. #
  108. # ClassProvides < ClassProvidesBase, Declaration
  109. # Declaration < Specification < SpecificationBase
  110. # ClassProvidesBase < SpecificationBase
  111. #
  112. # In order to have compatible instance layouts, we need to declare
  113. # the storage used by Specification and Declaration here (and
  114. # those classes must have ``__slots__ = ()``); fortunately this is
  115. # not a waste of space because those are the only two inheritance
  116. # trees. These all translate into tp_members in C.
  117. __slots__ = (
  118. # Things used here.
  119. '_implied',
  120. # Things used in Specification.
  121. '_dependents',
  122. '_bases',
  123. '_v_attrs',
  124. '__iro__',
  125. '__sro__',
  126. '__weakref__',
  127. )
  128. def providedBy(self, ob):
  129. """Is the interface implemented by an object
  130. """
  131. spec = providedBy(ob)
  132. return self in spec._implied
  133. def implementedBy(self, cls):
  134. """Test whether the specification is implemented by a class or factory.
  135. Raise TypeError if argument is neither a class nor a callable.
  136. """
  137. spec = implementedBy(cls)
  138. return self in spec._implied
  139. def isOrExtends(self, interface):
  140. """Is the interface the same as or extend the given interface
  141. """
  142. return interface in self._implied # pylint:disable=no-member
  143. __call__ = isOrExtends
  144. class NameAndModuleComparisonMixin(object):
  145. # Internal use. Implement the basic sorting operators (but not (in)equality
  146. # or hashing). Subclasses must provide ``__name__`` and ``__module__``
  147. # attributes. Subclasses will be mutually comparable; but because equality
  148. # and hashing semantics are missing from this class, take care in how
  149. # you define those two attributes: If you stick with the default equality
  150. # and hashing (identity based) you should make sure that all possible ``__name__``
  151. # and ``__module__`` pairs are unique ACROSS ALL SUBCLASSES. (Actually, pretty
  152. # much the same thing goes if you define equality and hashing to be based on
  153. # those two attributes: they must still be consistent ACROSS ALL SUBCLASSES.)
  154. # pylint:disable=assigning-non-slot
  155. __slots__ = ()
  156. def _compare(self, other):
  157. """
  158. Compare *self* to *other* based on ``__name__`` and ``__module__``.
  159. Return 0 if they are equal, return 1 if *self* is
  160. greater than *other*, and return -1 if *self* is less than
  161. *other*.
  162. If *other* does not have ``__name__`` or ``__module__``, then
  163. return ``NotImplemented``.
  164. .. caution::
  165. This allows comparison to things well outside the type hierarchy,
  166. perhaps not symmetrically.
  167. For example, ``class Foo(object)`` and ``class Foo(Interface)``
  168. in the same file would compare equal, depending on the order of
  169. operands. Writing code like this by hand would be unusual, but it could
  170. happen with dynamic creation of types and interfaces.
  171. None is treated as a pseudo interface that implies the loosest
  172. contact possible, no contract. For that reason, all interfaces
  173. sort before None.
  174. """
  175. if other is self:
  176. return 0
  177. if other is None:
  178. return -1
  179. n1 = (self.__name__, self.__module__)
  180. try:
  181. n2 = (other.__name__, other.__module__)
  182. except AttributeError:
  183. return NotImplemented
  184. # This spelling works under Python3, which doesn't have cmp().
  185. return (n1 > n2) - (n1 < n2)
  186. def __lt__(self, other):
  187. c = self._compare(other)
  188. if c is NotImplemented:
  189. return c
  190. return c < 0
  191. def __le__(self, other):
  192. c = self._compare(other)
  193. if c is NotImplemented:
  194. return c
  195. return c <= 0
  196. def __gt__(self, other):
  197. c = self._compare(other)
  198. if c is NotImplemented:
  199. return c
  200. return c > 0
  201. def __ge__(self, other):
  202. c = self._compare(other)
  203. if c is NotImplemented:
  204. return c
  205. return c >= 0
  206. @_use_c_impl
  207. class InterfaceBase(NameAndModuleComparisonMixin, SpecificationBasePy):
  208. """Base class that wants to be replaced with a C base :)
  209. """
  210. __slots__ = (
  211. '__name__',
  212. '__ibmodule__',
  213. '_v_cached_hash',
  214. )
  215. def __init__(self, name=None, module=None):
  216. self.__name__ = name
  217. self.__ibmodule__ = module
  218. def _call_conform(self, conform):
  219. raise NotImplementedError
  220. @property
  221. def __module_property__(self):
  222. # This is for _InterfaceMetaClass
  223. return self.__ibmodule__
  224. def __call__(self, obj, alternate=_marker):
  225. """Adapt an object to the interface
  226. """
  227. try:
  228. conform = obj.__conform__
  229. except AttributeError:
  230. conform = None
  231. if conform is not None:
  232. adapter = self._call_conform(conform)
  233. if adapter is not None:
  234. return adapter
  235. adapter = self.__adapt__(obj)
  236. if adapter is not None:
  237. return adapter
  238. if alternate is not _marker:
  239. return alternate
  240. raise TypeError("Could not adapt", obj, self)
  241. def __adapt__(self, obj):
  242. """Adapt an object to the receiver
  243. """
  244. if self.providedBy(obj):
  245. return obj
  246. for hook in adapter_hooks:
  247. adapter = hook(self, obj)
  248. if adapter is not None:
  249. return adapter
  250. return None
  251. def __hash__(self):
  252. # pylint:disable=assigning-non-slot,attribute-defined-outside-init
  253. try:
  254. return self._v_cached_hash
  255. except AttributeError:
  256. self._v_cached_hash = hash((self.__name__, self.__module__))
  257. return self._v_cached_hash
  258. def __eq__(self, other):
  259. c = self._compare(other)
  260. if c is NotImplemented:
  261. return c
  262. return c == 0
  263. def __ne__(self, other):
  264. if other is self:
  265. return False
  266. c = self._compare(other)
  267. if c is NotImplemented:
  268. return c
  269. return c != 0
  270. adapter_hooks = _use_c_impl([], 'adapter_hooks')
  271. class Specification(SpecificationBase):
  272. """Specifications
  273. An interface specification is used to track interface declarations
  274. and component registrations.
  275. This class is a base class for both interfaces themselves and for
  276. interface specifications (declarations).
  277. Specifications are mutable. If you reassign their bases, their
  278. relations with other specifications are adjusted accordingly.
  279. """
  280. __slots__ = ()
  281. # The root of all Specifications. This will be assigned `Interface`,
  282. # once it is defined.
  283. _ROOT = None
  284. # Copy some base class methods for speed
  285. isOrExtends = SpecificationBase.isOrExtends
  286. providedBy = SpecificationBase.providedBy
  287. def __init__(self, bases=()):
  288. # There are many leaf interfaces with no dependents,
  289. # and a few with very many. It's a heavily left-skewed
  290. # distribution. In a survey of Plone and Zope related packages
  291. # that loaded 2245 InterfaceClass objects and 2235 ClassProvides
  292. # instances, there were a total of 7000 Specification objects created.
  293. # 4700 had 0 dependents, 1400 had 1, 382 had 2 and so on. Only one
  294. # for <type> had 1664. So there's savings to be had deferring
  295. # the creation of dependents.
  296. self._dependents = None # type: weakref.WeakKeyDictionary
  297. self._bases = ()
  298. self._implied = {}
  299. self._v_attrs = None
  300. self.__iro__ = ()
  301. self.__sro__ = ()
  302. self.__bases__ = tuple(bases)
  303. @property
  304. def dependents(self):
  305. if self._dependents is None:
  306. self._dependents = weakref.WeakKeyDictionary()
  307. return self._dependents
  308. def subscribe(self, dependent):
  309. self._dependents[dependent] = self.dependents.get(dependent, 0) + 1
  310. def unsubscribe(self, dependent):
  311. try:
  312. n = self._dependents[dependent]
  313. except TypeError:
  314. raise KeyError(dependent)
  315. n -= 1
  316. if not n:
  317. del self.dependents[dependent]
  318. else:
  319. assert n > 0
  320. self.dependents[dependent] = n
  321. def __setBases(self, bases):
  322. # Remove ourselves as a dependent of our old bases
  323. for b in self.__bases__:
  324. b.unsubscribe(self)
  325. # Register ourselves as a dependent of our new bases
  326. self._bases = bases
  327. for b in bases:
  328. b.subscribe(self)
  329. self.changed(self)
  330. __bases__ = property(
  331. lambda self: self._bases,
  332. __setBases,
  333. )
  334. # This method exists for tests to override the way we call
  335. # ro.calculate_ro(), usually by adding extra kwargs. We don't
  336. # want to have a mutable dictionary as a class member that we pass
  337. # ourself because mutability is bad, and passing **kw is slower than
  338. # calling the bound function.
  339. _do_calculate_ro = calculate_ro
  340. def _calculate_sro(self):
  341. """
  342. Calculate and return the resolution order for this object, using its ``__bases__``.
  343. Ensures that ``Interface`` is always the last (lowest priority) element.
  344. """
  345. # We'd like to make Interface the lowest priority as a
  346. # property of the resolution order algorithm. That almost
  347. # works out naturally, but it fails when class inheritance has
  348. # some bases that DO implement an interface, and some that DO
  349. # NOT. In such a mixed scenario, you wind up with a set of
  350. # bases to consider that look like this: [[..., Interface],
  351. # [..., object], ...]. Depending on the order of inheritance,
  352. # Interface can wind up before or after object, and that can
  353. # happen at any point in the tree, meaning Interface can wind
  354. # up somewhere in the middle of the order. Since Interface is
  355. # treated as something that everything winds up implementing
  356. # anyway (a catch-all for things like adapters), having it high up
  357. # the order is bad. It's also bad to have it at the end, just before
  358. # some concrete class: concrete classes should be HIGHER priority than
  359. # interfaces (because there's only one class, but many implementations).
  360. #
  361. # One technically nice way to fix this would be to have
  362. # ``implementedBy(object).__bases__ = (Interface,)``
  363. #
  364. # But: (1) That fails for old-style classes and (2) that causes
  365. # everything to appear to *explicitly* implement Interface, when up
  366. # to this point it's been an implicit virtual sort of relationship.
  367. #
  368. # So we force the issue by mutating the resolution order.
  369. # Note that we let C3 use pre-computed __sro__ for our bases.
  370. # This requires that by the time this method is invoked, our bases
  371. # have settled their SROs. Thus, ``changed()`` must first
  372. # update itself before telling its descendents of changes.
  373. sro = self._do_calculate_ro(base_mros={
  374. b: b.__sro__
  375. for b in self.__bases__
  376. })
  377. root = self._ROOT
  378. if root is not None and sro and sro[-1] is not root:
  379. # In one dataset of 1823 Interface objects, 1117 ClassProvides objects,
  380. # sro[-1] was root 4496 times, and only not root 118 times. So it's
  381. # probably worth checking.
  382. # Once we don't have to deal with old-style classes,
  383. # we can add a check and only do this if base_count > 1,
  384. # if we tweak the bootstrapping for ``<implementedBy object>``
  385. sro = [
  386. x
  387. for x in sro
  388. if x is not root
  389. ]
  390. sro.append(root)
  391. return sro
  392. def changed(self, originally_changed):
  393. """
  394. We, or something we depend on, have changed.
  395. By the time this is called, the things we depend on,
  396. such as our bases, should themselves be stable.
  397. """
  398. self._v_attrs = None
  399. implied = self._implied
  400. implied.clear()
  401. ancestors = self._calculate_sro()
  402. self.__sro__ = tuple(ancestors)
  403. self.__iro__ = tuple([ancestor for ancestor in ancestors
  404. if isinstance(ancestor, InterfaceClass)
  405. ])
  406. for ancestor in ancestors:
  407. # We directly imply our ancestors:
  408. implied[ancestor] = ()
  409. # Now, advise our dependents of change
  410. # (being careful not to create the WeakKeyDictionary if not needed):
  411. for dependent in tuple(self._dependents.keys() if self._dependents else ()):
  412. dependent.changed(originally_changed)
  413. # Just in case something called get() at some point
  414. # during that process and we have a cycle of some sort
  415. # make sure we didn't cache incomplete results.
  416. self._v_attrs = None
  417. def interfaces(self):
  418. """Return an iterator for the interfaces in the specification.
  419. """
  420. seen = {}
  421. for base in self.__bases__:
  422. for interface in base.interfaces():
  423. if interface not in seen:
  424. seen[interface] = 1
  425. yield interface
  426. def extends(self, interface, strict=True):
  427. """Does the specification extend the given interface?
  428. Test whether an interface in the specification extends the
  429. given interface
  430. """
  431. return ((interface in self._implied)
  432. and
  433. ((not strict) or (self != interface))
  434. )
  435. def weakref(self, callback=None):
  436. return weakref.ref(self, callback)
  437. def get(self, name, default=None):
  438. """Query for an attribute description
  439. """
  440. attrs = self._v_attrs
  441. if attrs is None:
  442. attrs = self._v_attrs = {}
  443. attr = attrs.get(name)
  444. if attr is None:
  445. for iface in self.__iro__:
  446. attr = iface.direct(name)
  447. if attr is not None:
  448. attrs[name] = attr
  449. break
  450. return default if attr is None else attr
  451. class _InterfaceMetaClass(type):
  452. # Handling ``__module__`` on ``InterfaceClass`` is tricky. We need
  453. # to be able to read it on a type and get the expected string. We
  454. # also need to be able to set it on an instance and get the value
  455. # we set. So far so good. But what gets tricky is that we'd like
  456. # to store the value in the C structure (``InterfaceBase.__ibmodule__``) for
  457. # direct access during equality, sorting, and hashing. "No
  458. # problem, you think, I'll just use a property" (well, the C
  459. # equivalents, ``PyMemberDef`` or ``PyGetSetDef``).
  460. #
  461. # Except there is a problem. When a subclass is created, the
  462. # metaclass (``type``) always automatically puts the expected
  463. # string in the class's dictionary under ``__module__``, thus
  464. # overriding the property inherited from the superclass. Writing
  465. # ``Subclass.__module__`` still works, but
  466. # ``Subclass().__module__`` fails.
  467. #
  468. # There are multiple ways to work around this:
  469. #
  470. # (1) Define ``InterfaceBase.__getattribute__`` to watch for
  471. # ``__module__`` and return the C storage.
  472. #
  473. # This works, but slows down *all* attribute access (except,
  474. # ironically, to ``__module__``) by about 25% (40ns becomes 50ns)
  475. # (when implemented in C). Since that includes methods like
  476. # ``providedBy``, that's probably not acceptable.
  477. #
  478. # All the other methods involve modifying subclasses. This can be
  479. # done either on the fly in some cases, as instances are
  480. # constructed, or by using a metaclass. These next few can be done on the fly.
  481. #
  482. # (2) Make ``__module__`` a descriptor in each subclass dictionary.
  483. # It can't be a straight up ``@property`` descriptor, though, because accessing
  484. # it on the class returns a ``property`` object, not the desired string.
  485. #
  486. # (3) Implement a data descriptor (``__get__`` and ``__set__``)
  487. # that is both a subclass of string, and also does the redirect of
  488. # ``__module__`` to ``__ibmodule__`` and does the correct thing
  489. # with the ``instance`` argument to ``__get__`` is None (returns
  490. # the class's value.) (Why must it be a subclass of string? Because
  491. # when it' s in the class's dict, it's defined on an *instance* of the
  492. # metaclass; descriptors in an instance's dict aren't honored --- their
  493. # ``__get__`` is never invoked --- so it must also *be* the value we want
  494. # returned.)
  495. #
  496. # This works, preserves the ability to read and write
  497. # ``__module__``, and eliminates any penalty accessing other
  498. # attributes. But it slows down accessing ``__module__`` of
  499. # instances by 200% (40ns to 124ns), requires editing class dicts on the fly
  500. # (in InterfaceClass.__init__), thus slightly slowing down all interface creation,
  501. # and is ugly.
  502. #
  503. # (4) As in the last step, but make it a non-data descriptor (no ``__set__``).
  504. #
  505. # If you then *also* store a copy of ``__ibmodule__`` in
  506. # ``__module__`` in the instance's dict, reading works for both
  507. # class and instance and is full speed for instances. But the cost
  508. # is storage space, and you can't write to it anymore, not without
  509. # things getting out of sync.
  510. #
  511. # (Actually, ``__module__`` was never meant to be writable. Doing
  512. # so would break BTrees and normal dictionaries, as well as the
  513. # repr, maybe more.)
  514. #
  515. # That leaves us with a metaclass. (Recall that a class is an
  516. # instance of its metaclass, so properties/descriptors defined in
  517. # the metaclass are used when accessing attributes on the
  518. # instance/class. We'll use that to define ``__module__``.) Here
  519. # we can have our cake and eat it too: no extra storage, and
  520. # C-speed access to the underlying storage. The only substantial
  521. # cost is that metaclasses tend to make people's heads hurt. (But
  522. # still less than the descriptor-is-string, hopefully.)
  523. __slots__ = ()
  524. def __new__(cls, name, bases, attrs):
  525. # Figure out what module defined the interface.
  526. # This is copied from ``InterfaceClass.__init__``;
  527. # reviewers aren't sure how AttributeError or KeyError
  528. # could be raised.
  529. __module__ = sys._getframe(1).f_globals['__name__']
  530. # Get the C optimized __module__ accessor and give it
  531. # to the new class.
  532. moduledescr = InterfaceBase.__dict__['__module__']
  533. if isinstance(moduledescr, str):
  534. # We're working with the Python implementation,
  535. # not the C version
  536. moduledescr = InterfaceBase.__dict__['__module_property__']
  537. attrs['__module__'] = moduledescr
  538. kind = type.__new__(cls, name, bases, attrs)
  539. kind.__module = __module__
  540. return kind
  541. @property
  542. def __module__(cls):
  543. return cls.__module
  544. def __repr__(cls):
  545. return "<class '%s.%s'>" % (
  546. cls.__module,
  547. cls.__name__,
  548. )
  549. _InterfaceClassBase = _InterfaceMetaClass(
  550. 'InterfaceClass',
  551. # From least specific to most specific.
  552. (InterfaceBase, Specification, Element),
  553. {'__slots__': ()}
  554. )
  555. def interfacemethod(func):
  556. """
  557. Convert a method specification to an actual method of the interface.
  558. This is a decorator that functions like `staticmethod` et al.
  559. The primary use of this decorator is to allow interface definitions to
  560. define the ``__adapt__`` method, but other interface methods can be
  561. overridden this way too.
  562. .. seealso:: `zope.interface.interfaces.IInterfaceDeclaration.interfacemethod`
  563. """
  564. f_locals = sys._getframe(1).f_locals
  565. methods = f_locals.setdefault(INTERFACE_METHODS, {})
  566. methods[func.__name__] = func
  567. return _decorator_non_return
  568. class InterfaceClass(_InterfaceClassBase):
  569. """
  570. Prototype (scarecrow) Interfaces Implementation.
  571. Note that it is not possible to change the ``__name__`` or ``__module__``
  572. after an instance of this object has been constructed.
  573. """
  574. # We can't say this yet because we don't have enough
  575. # infrastructure in place.
  576. #
  577. #implements(IInterface)
  578. def __new__(cls, name=None, bases=(), attrs=None, __doc__=None, # pylint:disable=redefined-builtin
  579. __module__=None):
  580. assert isinstance(bases, tuple)
  581. attrs = attrs or {}
  582. needs_custom_class = attrs.pop(INTERFACE_METHODS, None)
  583. if needs_custom_class:
  584. needs_custom_class.update(
  585. {'__classcell__': attrs.pop('__classcell__')}
  586. if '__classcell__' in attrs
  587. else {}
  588. )
  589. if '__adapt__' in needs_custom_class:
  590. # We need to tell the C code to call this.
  591. needs_custom_class['_CALL_CUSTOM_ADAPT'] = 1
  592. if issubclass(cls, _InterfaceClassWithCustomMethods):
  593. cls_bases = (cls,)
  594. elif cls is InterfaceClass:
  595. cls_bases = (_InterfaceClassWithCustomMethods,)
  596. else:
  597. cls_bases = (cls, _InterfaceClassWithCustomMethods)
  598. cls = type(cls)( # pylint:disable=self-cls-assignment
  599. name + "<WithCustomMethods>",
  600. cls_bases,
  601. needs_custom_class
  602. )
  603. elif PY2 and bases and len(bases) > 1:
  604. bases_with_custom_methods = tuple(
  605. type(b)
  606. for b in bases
  607. if issubclass(type(b), _InterfaceClassWithCustomMethods)
  608. )
  609. # If we have a subclass of InterfaceClass in *bases*,
  610. # Python 3 is smart enough to pass that as *cls*, but Python
  611. # 2 just passes whatever the first base in *bases* is. This means that if
  612. # we have multiple inheritance, and one of our bases has already defined
  613. # a custom method like ``__adapt__``, we do the right thing automatically
  614. # and extend it on Python 3, but not necessarily on Python 2. To fix this, we need
  615. # to run the MRO algorithm and get the most derived base manually.
  616. # Note that this only works for consistent resolution orders
  617. if bases_with_custom_methods:
  618. cls = type( # pylint:disable=self-cls-assignment
  619. name + "<WithCustomMethods>",
  620. bases_with_custom_methods,
  621. {}
  622. ).__mro__[1] # Not the class we created, the most derived.
  623. return _InterfaceClassBase.__new__(cls)
  624. def __init__(self, name, bases=(), attrs=None, __doc__=None, # pylint:disable=redefined-builtin
  625. __module__=None):
  626. # We don't call our metaclass parent directly
  627. # pylint:disable=non-parent-init-called
  628. # pylint:disable=super-init-not-called
  629. if not all(isinstance(base, InterfaceClass) for base in bases):
  630. raise TypeError('Expected base interfaces')
  631. if attrs is None:
  632. attrs = {}
  633. if __module__ is None:
  634. __module__ = attrs.get('__module__')
  635. if isinstance(__module__, str):
  636. del attrs['__module__']
  637. else:
  638. try:
  639. # Figure out what module defined the interface.
  640. # This is how cPython figures out the module of
  641. # a class, but of course it does it in C. :-/
  642. __module__ = sys._getframe(1).f_globals['__name__']
  643. except (AttributeError, KeyError): # pragma: no cover
  644. pass
  645. InterfaceBase.__init__(self, name, __module__)
  646. # These asserts assisted debugging the metaclass
  647. # assert '__module__' not in self.__dict__
  648. # assert self.__ibmodule__ is self.__module__ is __module__
  649. d = attrs.get('__doc__')
  650. if d is not None:
  651. if not isinstance(d, Attribute):
  652. if __doc__ is None:
  653. __doc__ = d
  654. del attrs['__doc__']
  655. if __doc__ is None:
  656. __doc__ = ''
  657. Element.__init__(self, name, __doc__)
  658. tagged_data = attrs.pop(TAGGED_DATA, None)
  659. if tagged_data is not None:
  660. for key, val in tagged_data.items():
  661. self.setTaggedValue(key, val)
  662. Specification.__init__(self, bases)
  663. self.__attrs = self.__compute_attrs(attrs)
  664. self.__identifier__ = "%s.%s" % (__module__, name)
  665. def __compute_attrs(self, attrs):
  666. # Make sure that all recorded attributes (and methods) are of type
  667. # `Attribute` and `Method`
  668. def update_value(aname, aval):
  669. if isinstance(aval, Attribute):
  670. aval.interface = self
  671. if not aval.__name__:
  672. aval.__name__ = aname
  673. elif isinstance(aval, FunctionType):
  674. aval = fromFunction(aval, self, name=aname)
  675. else:
  676. raise InvalidInterface("Concrete attribute, " + aname)
  677. return aval
  678. return {
  679. aname: update_value(aname, aval)
  680. for aname, aval in attrs.items()
  681. if aname not in (
  682. # __locals__: Python 3 sometimes adds this.
  683. '__locals__',
  684. # __qualname__: PEP 3155 (Python 3.3+)
  685. '__qualname__',
  686. # __annotations__: PEP 3107 (Python 3.0+)
  687. '__annotations__',
  688. )
  689. and aval is not _decorator_non_return
  690. }
  691. def interfaces(self):
  692. """Return an iterator for the interfaces in the specification.
  693. """
  694. yield self
  695. def getBases(self):
  696. return self.__bases__
  697. def isEqualOrExtendedBy(self, other):
  698. """Same interface or extends?"""
  699. return self == other or other.extends(self)
  700. def names(self, all=False): # pylint:disable=redefined-builtin
  701. """Return the attribute names defined by the interface."""
  702. if not all:
  703. return self.__attrs.keys()
  704. r = self.__attrs.copy()
  705. for base in self.__bases__:
  706. r.update(dict.fromkeys(base.names(all)))
  707. return r.keys()
  708. def __iter__(self):
  709. return iter(self.names(all=True))
  710. def namesAndDescriptions(self, all=False): # pylint:disable=redefined-builtin
  711. """Return attribute names and descriptions defined by interface."""
  712. if not all:
  713. return self.__attrs.items()
  714. r = {}
  715. for base in self.__bases__[::-1]:
  716. r.update(dict(base.namesAndDescriptions(all)))
  717. r.update(self.__attrs)
  718. return r.items()
  719. def getDescriptionFor(self, name):
  720. """Return the attribute description for the given name."""
  721. r = self.get(name)
  722. if r is not None:
  723. return r
  724. raise KeyError(name)
  725. __getitem__ = getDescriptionFor
  726. def __contains__(self, name):
  727. return self.get(name) is not None
  728. def direct(self, name):
  729. return self.__attrs.get(name)
  730. def queryDescriptionFor(self, name, default=None):
  731. return self.get(name, default)
  732. def validateInvariants(self, obj, errors=None):
  733. """validate object to defined invariants."""
  734. for iface in self.__iro__:
  735. for invariant in iface.queryDirectTaggedValue('invariants', ()):
  736. try:
  737. invariant(obj)
  738. except Invalid as error:
  739. if errors is not None:
  740. errors.append(error)
  741. else:
  742. raise
  743. if errors:
  744. raise Invalid(errors)
  745. def queryTaggedValue(self, tag, default=None):
  746. """
  747. Queries for the value associated with *tag*, returning it from the nearest
  748. interface in the ``__iro__``.
  749. If not found, returns *default*.
  750. """
  751. for iface in self.__iro__:
  752. value = iface.queryDirectTaggedValue(tag, _marker)
  753. if value is not _marker:
  754. return value
  755. return default
  756. def getTaggedValue(self, tag):
  757. """ Returns the value associated with 'tag'. """
  758. value = self.queryTaggedValue(tag, default=_marker)
  759. if value is _marker:
  760. raise KeyError(tag)
  761. return value
  762. def getTaggedValueTags(self):
  763. """ Returns a list of all tags. """
  764. keys = set()
  765. for base in self.__iro__:
  766. keys.update(base.getDirectTaggedValueTags())
  767. return keys
  768. def __repr__(self):
  769. try:
  770. return self._v_repr
  771. except AttributeError:
  772. name = str(self)
  773. r = "<%s %s>" % (self.__class__.__name__, name)
  774. self._v_repr = r # pylint:disable=attribute-defined-outside-init
  775. return r
  776. def __str__(self):
  777. name = self.__name__
  778. m = self.__ibmodule__
  779. if m:
  780. name = '%s.%s' % (m, name)
  781. return name
  782. def _call_conform(self, conform):
  783. try:
  784. return conform(self)
  785. except TypeError: # pragma: no cover
  786. # We got a TypeError. It might be an error raised by
  787. # the __conform__ implementation, or *we* may have
  788. # made the TypeError by calling an unbound method
  789. # (object is a class). In the later case, we behave
  790. # as though there is no __conform__ method. We can
  791. # detect this case by checking whether there is more
  792. # than one traceback object in the traceback chain:
  793. if sys.exc_info()[2].tb_next is not None:
  794. # There is more than one entry in the chain, so
  795. # reraise the error:
  796. raise
  797. # This clever trick is from Phillip Eby
  798. return None # pragma: no cover
  799. def __reduce__(self):
  800. return self.__name__
  801. Interface = InterfaceClass("Interface", __module__='zope.interface')
  802. # Interface is the only member of its own SRO.
  803. Interface._calculate_sro = lambda: (Interface,)
  804. Interface.changed(Interface)
  805. assert Interface.__sro__ == (Interface,)
  806. Specification._ROOT = Interface
  807. ro._ROOT = Interface
  808. class _InterfaceClassWithCustomMethods(InterfaceClass):
  809. """
  810. Marker class for interfaces with custom methods that override InterfaceClass methods.
  811. """
  812. class Attribute(Element):
  813. """Attribute descriptions
  814. """
  815. # We can't say this yet because we don't have enough
  816. # infrastructure in place.
  817. #
  818. # implements(IAttribute)
  819. interface = None
  820. def _get_str_info(self):
  821. """Return extra data to put at the end of __str__."""
  822. return ""
  823. def __str__(self):
  824. of = ''
  825. if self.interface is not None:
  826. of = self.interface.__module__ + '.' + self.interface.__name__ + '.'
  827. # self.__name__ may be None during construction (e.g., debugging)
  828. return of + (self.__name__ or '<unknown>') + self._get_str_info()
  829. def __repr__(self):
  830. return "<%s.%s object at 0x%x %s>" % (
  831. type(self).__module__,
  832. type(self).__name__,
  833. id(self),
  834. self
  835. )
  836. class Method(Attribute):
  837. """Method interfaces
  838. The idea here is that you have objects that describe methods.
  839. This provides an opportunity for rich meta-data.
  840. """
  841. # We can't say this yet because we don't have enough
  842. # infrastructure in place.
  843. #
  844. # implements(IMethod)
  845. positional = required = ()
  846. _optional = varargs = kwargs = None
  847. def _get_optional(self):
  848. if self._optional is None:
  849. return {}
  850. return self._optional
  851. def _set_optional(self, opt):
  852. self._optional = opt
  853. def _del_optional(self):
  854. self._optional = None
  855. optional = property(_get_optional, _set_optional, _del_optional)
  856. def __call__(self, *args, **kw):
  857. raise BrokenImplementation(self.interface, self.__name__)
  858. def getSignatureInfo(self):
  859. return {'positional': self.positional,
  860. 'required': self.required,
  861. 'optional': self.optional,
  862. 'varargs': self.varargs,
  863. 'kwargs': self.kwargs,
  864. }
  865. def getSignatureString(self):
  866. sig = []
  867. for v in self.positional:
  868. sig.append(v)
  869. if v in self.optional.keys():
  870. sig[-1] += "=" + repr(self.optional[v])
  871. if self.varargs:
  872. sig.append("*" + self.varargs)
  873. if self.kwargs:
  874. sig.append("**" + self.kwargs)
  875. return "(%s)" % ", ".join(sig)
  876. _get_str_info = getSignatureString
  877. def fromFunction(func, interface=None, imlevel=0, name=None):
  878. name = name or func.__name__
  879. method = Method(name, func.__doc__)
  880. defaults = getattr(func, '__defaults__', None) or ()
  881. code = func.__code__
  882. # Number of positional arguments
  883. na = code.co_argcount - imlevel
  884. names = code.co_varnames[imlevel:]
  885. opt = {}
  886. # Number of required arguments
  887. defaults_count = len(defaults)
  888. if not defaults_count:
  889. # PyPy3 uses ``__defaults_count__`` for builtin methods
  890. # like ``dict.pop``. Surprisingly, these don't have recorded
  891. # ``__defaults__``
  892. defaults_count = getattr(func, '__defaults_count__', 0)
  893. nr = na - defaults_count
  894. if nr < 0:
  895. defaults = defaults[-nr:]
  896. nr = 0
  897. # Determine the optional arguments.
  898. opt.update(dict(zip(names[nr:], defaults)))
  899. method.positional = names[:na]
  900. method.required = names[:nr]
  901. method.optional = opt
  902. argno = na
  903. # Determine the function's variable argument's name (i.e. *args)
  904. if code.co_flags & CO_VARARGS:
  905. method.varargs = names[argno]
  906. argno = argno + 1
  907. else:
  908. method.varargs = None
  909. # Determine the function's keyword argument's name (i.e. **kw)
  910. if code.co_flags & CO_VARKEYWORDS:
  911. method.kwargs = names[argno]
  912. else:
  913. method.kwargs = None
  914. method.interface = interface
  915. for key, value in func.__dict__.items():
  916. method.setTaggedValue(key, value)
  917. return method
  918. def fromMethod(meth, interface=None, name=None):
  919. if isinstance(meth, MethodType):
  920. func = meth.__func__
  921. else:
  922. func = meth
  923. return fromFunction(func, interface, imlevel=1, name=name)
  924. # Now we can create the interesting interfaces and wire them up:
  925. def _wire():
  926. from zope.interface.declarations import classImplements
  927. # From lest specific to most specific.
  928. from zope.interface.interfaces import IElement
  929. classImplements(Element, IElement)
  930. from zope.interface.interfaces import IAttribute
  931. classImplements(Attribute, IAttribute)
  932. from zope.interface.interfaces import IMethod
  933. classImplements(Method, IMethod)
  934. from zope.interface.interfaces import ISpecification
  935. classImplements(Specification, ISpecification)
  936. from zope.interface.interfaces import IInterface
  937. classImplements(InterfaceClass, IInterface)
  938. # We import this here to deal with module dependencies.
  939. # pylint:disable=wrong-import-position
  940. from zope.interface.declarations import implementedBy
  941. from zope.interface.declarations import providedBy
  942. from zope.interface.exceptions import InvalidInterface
  943. from zope.interface.exceptions import BrokenImplementation
  944. # This ensures that ``Interface`` winds up in the flattened()
  945. # list of the immutable declaration. It correctly overrides changed()
  946. # as a no-op, so we bypass that.
  947. from zope.interface.declarations import _empty
  948. Specification.changed(_empty, _empty)