interface.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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. from __future__ import generators
  17. import sys
  18. from types import MethodType
  19. from types import FunctionType
  20. import warnings
  21. import weakref
  22. from zope.interface.exceptions import Invalid
  23. from zope.interface.ro import ro
  24. CO_VARARGS = 4
  25. CO_VARKEYWORDS = 8
  26. TAGGED_DATA = '__interface_tagged_values__'
  27. _decorator_non_return = object()
  28. def invariant(call):
  29. f_locals = sys._getframe(1).f_locals
  30. tags = f_locals.setdefault(TAGGED_DATA, {})
  31. invariants = tags.setdefault('invariants', [])
  32. invariants.append(call)
  33. return _decorator_non_return
  34. def taggedValue(key, value):
  35. """Attaches a tagged value to an interface at definition time."""
  36. f_locals = sys._getframe(1).f_locals
  37. tagged_values = f_locals.setdefault(TAGGED_DATA, {})
  38. tagged_values[key] = value
  39. return _decorator_non_return
  40. class Element(object):
  41. # We can't say this yet because we don't have enough
  42. # infrastructure in place.
  43. #
  44. #implements(IElement)
  45. def __init__(self, __name__, __doc__=''):
  46. """Create an 'attribute' description
  47. """
  48. if not __doc__ and __name__.find(' ') >= 0:
  49. __doc__ = __name__
  50. __name__ = None
  51. self.__name__=__name__
  52. self.__doc__=__doc__
  53. self.__tagged_values = {}
  54. def getName(self):
  55. """ Returns the name of the object. """
  56. return self.__name__
  57. def getDoc(self):
  58. """ Returns the documentation for the object. """
  59. return self.__doc__
  60. def getTaggedValue(self, tag):
  61. """ Returns the value associated with 'tag'. """
  62. return self.__tagged_values[tag]
  63. def queryTaggedValue(self, tag, default=None):
  64. """ Returns the value associated with 'tag'. """
  65. return self.__tagged_values.get(tag, default)
  66. def getTaggedValueTags(self):
  67. """ Returns a list of all tags. """
  68. return self.__tagged_values.keys()
  69. def setTaggedValue(self, tag, value):
  70. """ Associates 'value' with 'key'. """
  71. self.__tagged_values[tag] = value
  72. class SpecificationBasePy(object):
  73. def providedBy(self, ob):
  74. """Is the interface implemented by an object
  75. """
  76. spec = providedBy(ob)
  77. return self in spec._implied
  78. def implementedBy(self, cls):
  79. """Test whether the specification is implemented by a class or factory.
  80. Raise TypeError if argument is neither a class nor a callable.
  81. """
  82. spec = implementedBy(cls)
  83. return self in spec._implied
  84. def isOrExtends(self, interface):
  85. """Is the interface the same as or extend the given interface
  86. """
  87. return interface in self._implied
  88. __call__ = isOrExtends
  89. SpecificationBase = SpecificationBasePy
  90. try:
  91. from zope.interface._zope_interface_coptimizations import SpecificationBase
  92. except ImportError:
  93. pass
  94. _marker = object()
  95. class InterfaceBasePy(object):
  96. """Base class that wants to be replaced with a C base :)
  97. """
  98. def __call__(self, obj, alternate=_marker):
  99. """Adapt an object to the interface
  100. """
  101. conform = getattr(obj, '__conform__', None)
  102. if conform is not None:
  103. adapter = self._call_conform(conform)
  104. if adapter is not None:
  105. return adapter
  106. adapter = self.__adapt__(obj)
  107. if adapter is not None:
  108. return adapter
  109. elif alternate is not _marker:
  110. return alternate
  111. else:
  112. raise TypeError("Could not adapt", obj, self)
  113. def __adapt__(self, obj):
  114. """Adapt an object to the reciever
  115. """
  116. if self.providedBy(obj):
  117. return obj
  118. for hook in adapter_hooks:
  119. adapter = hook(self, obj)
  120. if adapter is not None:
  121. return adapter
  122. InterfaceBase = InterfaceBasePy
  123. try:
  124. from zope.interface._zope_interface_coptimizations import InterfaceBase
  125. except ImportError:
  126. pass
  127. adapter_hooks = []
  128. try:
  129. from zope.interface._zope_interface_coptimizations import adapter_hooks
  130. except ImportError:
  131. pass
  132. class Specification(SpecificationBase):
  133. """Specifications
  134. An interface specification is used to track interface declarations
  135. and component registrations.
  136. This class is a base class for both interfaces themselves and for
  137. interface specifications (declarations).
  138. Specifications are mutable. If you reassign their bases, their
  139. relations with other specifications are adjusted accordingly.
  140. """
  141. # Copy some base class methods for speed
  142. isOrExtends = SpecificationBase.isOrExtends
  143. providedBy = SpecificationBase.providedBy
  144. def __init__(self, bases=()):
  145. self._implied = {}
  146. self.dependents = weakref.WeakKeyDictionary()
  147. self.__bases__ = tuple(bases)
  148. def subscribe(self, dependent):
  149. self.dependents[dependent] = self.dependents.get(dependent, 0) + 1
  150. def unsubscribe(self, dependent):
  151. n = self.dependents.get(dependent, 0) - 1
  152. if not n:
  153. del self.dependents[dependent]
  154. elif n > 0:
  155. self.dependents[dependent] = n
  156. else:
  157. raise KeyError(dependent)
  158. def __setBases(self, bases):
  159. # Register ourselves as a dependent of our old bases
  160. for b in self.__bases__:
  161. b.unsubscribe(self)
  162. # Register ourselves as a dependent of our bases
  163. self.__dict__['__bases__'] = bases
  164. for b in bases:
  165. b.subscribe(self)
  166. self.changed(self)
  167. __bases__ = property(
  168. lambda self: self.__dict__.get('__bases__', ()),
  169. __setBases,
  170. )
  171. def changed(self, originally_changed):
  172. """We, or something we depend on, have changed
  173. """
  174. try:
  175. del self._v_attrs
  176. except AttributeError:
  177. pass
  178. implied = self._implied
  179. implied.clear()
  180. ancestors = ro(self)
  181. try:
  182. if Interface not in ancestors:
  183. ancestors.append(Interface)
  184. except NameError:
  185. pass # defining Interface itself
  186. self.__sro__ = tuple(ancestors)
  187. self.__iro__ = tuple([ancestor for ancestor in ancestors
  188. if isinstance(ancestor, InterfaceClass)
  189. ])
  190. for ancestor in ancestors:
  191. # We directly imply our ancestors:
  192. implied[ancestor] = ()
  193. # Now, advise our dependents of change:
  194. for dependent in tuple(self.dependents.keys()):
  195. dependent.changed(originally_changed)
  196. def interfaces(self):
  197. """Return an iterator for the interfaces in the specification.
  198. """
  199. seen = {}
  200. for base in self.__bases__:
  201. for interface in base.interfaces():
  202. if interface not in seen:
  203. seen[interface] = 1
  204. yield interface
  205. def extends(self, interface, strict=True):
  206. """Does the specification extend the given interface?
  207. Test whether an interface in the specification extends the
  208. given interface
  209. """
  210. return ((interface in self._implied)
  211. and
  212. ((not strict) or (self != interface))
  213. )
  214. def weakref(self, callback=None):
  215. return weakref.ref(self, callback)
  216. def get(self, name, default=None):
  217. """Query for an attribute description
  218. """
  219. try:
  220. attrs = self._v_attrs
  221. except AttributeError:
  222. attrs = self._v_attrs = {}
  223. attr = attrs.get(name)
  224. if attr is None:
  225. for iface in self.__iro__:
  226. attr = iface.direct(name)
  227. if attr is not None:
  228. attrs[name] = attr
  229. break
  230. if attr is None:
  231. return default
  232. else:
  233. return attr
  234. class InterfaceClass(Element, InterfaceBase, Specification):
  235. """Prototype (scarecrow) Interfaces Implementation."""
  236. # We can't say this yet because we don't have enough
  237. # infrastructure in place.
  238. #
  239. #implements(IInterface)
  240. def __init__(self, name, bases=(), attrs=None, __doc__=None,
  241. __module__=None):
  242. if attrs is None:
  243. attrs = {}
  244. if __module__ is None:
  245. __module__ = attrs.get('__module__')
  246. if isinstance(__module__, str):
  247. del attrs['__module__']
  248. else:
  249. try:
  250. # Figure out what module defined the interface.
  251. # This is how cPython figures out the module of
  252. # a class, but of course it does it in C. :-/
  253. __module__ = sys._getframe(1).f_globals['__name__']
  254. except (AttributeError, KeyError): # pragma: no cover
  255. pass
  256. self.__module__ = __module__
  257. d = attrs.get('__doc__')
  258. if d is not None:
  259. if not isinstance(d, Attribute):
  260. if __doc__ is None:
  261. __doc__ = d
  262. del attrs['__doc__']
  263. if __doc__ is None:
  264. __doc__ = ''
  265. Element.__init__(self, name, __doc__)
  266. tagged_data = attrs.pop(TAGGED_DATA, None)
  267. if tagged_data is not None:
  268. for key, val in tagged_data.items():
  269. self.setTaggedValue(key, val)
  270. for base in bases:
  271. if not isinstance(base, InterfaceClass):
  272. raise TypeError('Expected base interfaces')
  273. Specification.__init__(self, bases)
  274. # Make sure that all recorded attributes (and methods) are of type
  275. # `Attribute` and `Method`
  276. for name, attr in list(attrs.items()):
  277. if name in ('__locals__', '__qualname__'):
  278. # __locals__: Python 3 sometimes adds this.
  279. # __qualname__: PEP 3155 (Python 3.3+)
  280. del attrs[name]
  281. continue
  282. if isinstance(attr, Attribute):
  283. attr.interface = self
  284. if not attr.__name__:
  285. attr.__name__ = name
  286. elif isinstance(attr, FunctionType):
  287. attrs[name] = fromFunction(attr, self, name=name)
  288. elif attr is _decorator_non_return:
  289. del attrs[name]
  290. else:
  291. raise InvalidInterface("Concrete attribute, " + name)
  292. self.__attrs = attrs
  293. self.__identifier__ = "%s.%s" % (self.__module__, self.__name__)
  294. def interfaces(self):
  295. """Return an iterator for the interfaces in the specification.
  296. """
  297. yield self
  298. def getBases(self):
  299. return self.__bases__
  300. def isEqualOrExtendedBy(self, other):
  301. """Same interface or extends?"""
  302. return self == other or other.extends(self)
  303. def names(self, all=False):
  304. """Return the attribute names defined by the interface."""
  305. if not all:
  306. return self.__attrs.keys()
  307. r = self.__attrs.copy()
  308. for base in self.__bases__:
  309. r.update(dict.fromkeys(base.names(all)))
  310. return r.keys()
  311. def __iter__(self):
  312. return iter(self.names(all=True))
  313. def namesAndDescriptions(self, all=False):
  314. """Return attribute names and descriptions defined by interface."""
  315. if not all:
  316. return self.__attrs.items()
  317. r = {}
  318. for base in self.__bases__[::-1]:
  319. r.update(dict(base.namesAndDescriptions(all)))
  320. r.update(self.__attrs)
  321. return r.items()
  322. def getDescriptionFor(self, name):
  323. """Return the attribute description for the given name."""
  324. r = self.get(name)
  325. if r is not None:
  326. return r
  327. raise KeyError(name)
  328. __getitem__ = getDescriptionFor
  329. def __contains__(self, name):
  330. return self.get(name) is not None
  331. def direct(self, name):
  332. return self.__attrs.get(name)
  333. def queryDescriptionFor(self, name, default=None):
  334. return self.get(name, default)
  335. def validateInvariants(self, obj, errors=None):
  336. """validate object to defined invariants."""
  337. for call in self.queryTaggedValue('invariants', []):
  338. try:
  339. call(obj)
  340. except Invalid as e:
  341. if errors is None:
  342. raise
  343. else:
  344. errors.append(e)
  345. for base in self.__bases__:
  346. try:
  347. base.validateInvariants(obj, errors)
  348. except Invalid:
  349. if errors is None:
  350. raise
  351. if errors:
  352. raise Invalid(errors)
  353. def __repr__(self): # pragma: no cover
  354. try:
  355. return self._v_repr
  356. except AttributeError:
  357. name = self.__name__
  358. m = self.__module__
  359. if m:
  360. name = '%s.%s' % (m, name)
  361. r = "<%s %s>" % (self.__class__.__name__, name)
  362. self._v_repr = r
  363. return r
  364. def _call_conform(self, conform):
  365. try:
  366. return conform(self)
  367. except TypeError: # pragma: no cover
  368. # We got a TypeError. It might be an error raised by
  369. # the __conform__ implementation, or *we* may have
  370. # made the TypeError by calling an unbound method
  371. # (object is a class). In the later case, we behave
  372. # as though there is no __conform__ method. We can
  373. # detect this case by checking whether there is more
  374. # than one traceback object in the traceback chain:
  375. if sys.exc_info()[2].tb_next is not None:
  376. # There is more than one entry in the chain, so
  377. # reraise the error:
  378. raise
  379. # This clever trick is from Phillip Eby
  380. return None # pragma: no cover
  381. def __reduce__(self):
  382. return self.__name__
  383. def __cmp(self, other):
  384. # Yes, I did mean to name this __cmp, rather than __cmp__.
  385. # It is a private method used by __lt__ and __gt__.
  386. # I don't want to override __eq__ because I want the default
  387. # __eq__, which is really fast.
  388. """Make interfaces sortable
  389. TODO: It would ne nice if:
  390. More specific interfaces should sort before less specific ones.
  391. Otherwise, sort on name and module.
  392. But this is too complicated, and we're going to punt on it
  393. for now.
  394. For now, sort on interface and module name.
  395. None is treated as a pseudo interface that implies the loosest
  396. contact possible, no contract. For that reason, all interfaces
  397. sort before None.
  398. """
  399. if other is None:
  400. return -1
  401. n1 = (getattr(self, '__name__', ''), getattr(self, '__module__', ''))
  402. n2 = (getattr(other, '__name__', ''), getattr(other, '__module__', ''))
  403. # This spelling works under Python3, which doesn't have cmp().
  404. return (n1 > n2) - (n1 < n2)
  405. def __hash__(self):
  406. d = self.__dict__
  407. if '__module__' not in d or '__name__' not in d: # pragma: no cover
  408. warnings.warn('Hashing uninitialized InterfaceClass instance')
  409. return 1
  410. return hash((self.__name__, self.__module__))
  411. def __eq__(self, other):
  412. c = self.__cmp(other)
  413. return c == 0
  414. def __ne__(self, other):
  415. c = self.__cmp(other)
  416. return c != 0
  417. def __lt__(self, other):
  418. c = self.__cmp(other)
  419. return c < 0
  420. def __le__(self, other):
  421. c = self.__cmp(other)
  422. return c <= 0
  423. def __gt__(self, other):
  424. c = self.__cmp(other)
  425. return c > 0
  426. def __ge__(self, other):
  427. c = self.__cmp(other)
  428. return c >= 0
  429. Interface = InterfaceClass("Interface", __module__ = 'zope.interface')
  430. class Attribute(Element):
  431. """Attribute descriptions
  432. """
  433. # We can't say this yet because we don't have enough
  434. # infrastructure in place.
  435. #
  436. # implements(IAttribute)
  437. interface = None
  438. class Method(Attribute):
  439. """Method interfaces
  440. The idea here is that you have objects that describe methods.
  441. This provides an opportunity for rich meta-data.
  442. """
  443. # We can't say this yet because we don't have enough
  444. # infrastructure in place.
  445. #
  446. # implements(IMethod)
  447. positional = required = ()
  448. _optional = varargs = kwargs = None
  449. def _get_optional(self):
  450. if self._optional is None:
  451. return {}
  452. return self._optional
  453. def _set_optional(self, opt):
  454. self._optional = opt
  455. def _del_optional(self):
  456. self._optional = None
  457. optional = property(_get_optional, _set_optional, _del_optional)
  458. def __call__(self, *args, **kw):
  459. raise BrokenImplementation(self.interface, self.__name__)
  460. def getSignatureInfo(self):
  461. return {'positional': self.positional,
  462. 'required': self.required,
  463. 'optional': self.optional,
  464. 'varargs': self.varargs,
  465. 'kwargs': self.kwargs,
  466. }
  467. def getSignatureString(self):
  468. sig = []
  469. for v in self.positional:
  470. sig.append(v)
  471. if v in self.optional.keys():
  472. sig[-1] += "=" + repr(self.optional[v])
  473. if self.varargs:
  474. sig.append("*" + self.varargs)
  475. if self.kwargs:
  476. sig.append("**" + self.kwargs)
  477. return "(%s)" % ", ".join(sig)
  478. def fromFunction(func, interface=None, imlevel=0, name=None):
  479. name = name or func.__name__
  480. method = Method(name, func.__doc__)
  481. defaults = getattr(func, '__defaults__', None) or ()
  482. code = func.__code__
  483. # Number of positional arguments
  484. na = code.co_argcount-imlevel
  485. names = code.co_varnames[imlevel:]
  486. opt = {}
  487. # Number of required arguments
  488. nr = na-len(defaults)
  489. if nr < 0:
  490. defaults=defaults[-nr:]
  491. nr = 0
  492. # Determine the optional arguments.
  493. opt.update(dict(zip(names[nr:], defaults)))
  494. method.positional = names[:na]
  495. method.required = names[:nr]
  496. method.optional = opt
  497. argno = na
  498. # Determine the function's variable argument's name (i.e. *args)
  499. if code.co_flags & CO_VARARGS:
  500. method.varargs = names[argno]
  501. argno = argno + 1
  502. else:
  503. method.varargs = None
  504. # Determine the function's keyword argument's name (i.e. **kw)
  505. if code.co_flags & CO_VARKEYWORDS:
  506. method.kwargs = names[argno]
  507. else:
  508. method.kwargs = None
  509. method.interface = interface
  510. for key, value in func.__dict__.items():
  511. method.setTaggedValue(key, value)
  512. return method
  513. def fromMethod(meth, interface=None, name=None):
  514. if isinstance(meth, MethodType):
  515. func = meth.__func__
  516. else:
  517. func = meth
  518. return fromFunction(func, interface, imlevel=1, name=name)
  519. # Now we can create the interesting interfaces and wire them up:
  520. def _wire():
  521. from zope.interface.declarations import classImplements
  522. from zope.interface.interfaces import IAttribute
  523. classImplements(Attribute, IAttribute)
  524. from zope.interface.interfaces import IMethod
  525. classImplements(Method, IMethod)
  526. from zope.interface.interfaces import IInterface
  527. classImplements(InterfaceClass, IInterface)
  528. from zope.interface.interfaces import ISpecification
  529. classImplements(Specification, ISpecification)
  530. # We import this here to deal with module dependencies.
  531. from zope.interface.declarations import implementedBy
  532. from zope.interface.declarations import providedBy
  533. from zope.interface.exceptions import InvalidInterface
  534. from zope.interface.exceptions import BrokenImplementation