declarations.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  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 InterfaceClass
  29. from zope.interface.interface import SpecificationBase
  30. from zope.interface.interface import Specification
  31. from zope.interface._compat import CLASS_TYPES as DescriptorAwareMetaClasses
  32. from zope.interface._compat import PYTHON3
  33. # Registry of class-implementation specifications
  34. BuiltinImplementationSpecifications = {}
  35. _ADVICE_ERROR = ('Class advice impossible in Python3. '
  36. 'Use the @%s class decorator instead.')
  37. _ADVICE_WARNING = ('The %s API is deprecated, and will not work in Python3 '
  38. 'Use the @%s class decorator instead.')
  39. class named(object):
  40. def __init__(self, name):
  41. self.name = name
  42. def __call__(self, ob):
  43. ob.__component_name__ = self.name
  44. return ob
  45. class Declaration(Specification):
  46. """Interface declarations"""
  47. def __init__(self, *interfaces):
  48. Specification.__init__(self, _normalizeargs(interfaces))
  49. def changed(self, originally_changed):
  50. Specification.changed(self, originally_changed)
  51. try:
  52. del self._v_attrs
  53. except AttributeError:
  54. pass
  55. def __contains__(self, interface):
  56. """Test whether an interface is in the specification
  57. """
  58. return self.extends(interface) and interface in self.interfaces()
  59. def __iter__(self):
  60. """Return an iterator for the interfaces in the specification
  61. """
  62. return self.interfaces()
  63. def flattened(self):
  64. """Return an iterator of all included and extended interfaces
  65. """
  66. return iter(self.__iro__)
  67. def __sub__(self, other):
  68. """Remove interfaces from a specification
  69. """
  70. return Declaration(
  71. *[i for i in self.interfaces()
  72. if not [j for j in other.interfaces()
  73. if i.extends(j, 0)]
  74. ]
  75. )
  76. def __add__(self, other):
  77. """Add two specifications or a specification and an interface
  78. """
  79. seen = {}
  80. result = []
  81. for i in self.interfaces():
  82. seen[i] = 1
  83. result.append(i)
  84. for i in other.interfaces():
  85. if i not in seen:
  86. seen[i] = 1
  87. result.append(i)
  88. return Declaration(*result)
  89. __radd__ = __add__
  90. ##############################################################################
  91. #
  92. # Implementation specifications
  93. #
  94. # These specify interfaces implemented by instances of classes
  95. class Implements(Declaration):
  96. # class whose specification should be used as additional base
  97. inherit = None
  98. # interfaces actually declared for a class
  99. declared = ()
  100. __name__ = '?'
  101. @classmethod
  102. def named(cls, name, *interfaces):
  103. # Implementation method: Produce an Implements interface with
  104. # a fully fleshed out __name__ before calling the constructor, which
  105. # sets bases to the given interfaces and which may pass this object to
  106. # other objects (e.g., to adjust dependents). If they're sorting or comparing
  107. # by name, this needs to be set.
  108. inst = cls.__new__(cls)
  109. inst.__name__ = name
  110. inst.__init__(*interfaces)
  111. return inst
  112. def __repr__(self):
  113. return '<implementedBy %s>' % (self.__name__)
  114. def __reduce__(self):
  115. return implementedBy, (self.inherit, )
  116. def __cmp(self, other):
  117. # Yes, I did mean to name this __cmp, rather than __cmp__.
  118. # It is a private method used by __lt__ and __gt__.
  119. # This is based on, and compatible with, InterfaceClass.
  120. # (The two must be mutually comparable to be able to work in e.g., BTrees.)
  121. # Instances of this class generally don't have a __module__ other than
  122. # `zope.interface.declarations`, whereas they *do* have a __name__ that is the
  123. # fully qualified name of the object they are representing.
  124. # Note, though, that equality and hashing are still identity based. This
  125. # accounts for things like nested objects that have the same name (typically
  126. # only in tests) and is consistent with pickling. As far as comparisons to InterfaceClass
  127. # goes, we'll never have equal name and module to those, so we're still consistent there.
  128. # Instances of this class are essentially intended to be unique and are
  129. # heavily cached (note how our __reduce__ handles this) so having identity
  130. # based hash and eq should also work.
  131. if other is None:
  132. return -1
  133. n1 = (self.__name__, self.__module__)
  134. n2 = (getattr(other, '__name__', ''), getattr(other, '__module__', ''))
  135. # This spelling works under Python3, which doesn't have cmp().
  136. return (n1 > n2) - (n1 < n2)
  137. def __hash__(self):
  138. return Declaration.__hash__(self)
  139. # We want equality to be based on identity. However, we can't actually
  140. # implement __eq__/__ne__ to do this because sometimes we get wrapped in a proxy.
  141. # We need to let the proxy types implement these methods so they can handle unwrapping
  142. # and then rely on: (1) the interpreter automatically changing `implements == proxy` into
  143. # `proxy == implements` (which will call proxy.__eq__ to do the unwrapping) and then
  144. # (2) the default equality semantics being identity based.
  145. def __lt__(self, other):
  146. c = self.__cmp(other)
  147. return c < 0
  148. def __le__(self, other):
  149. c = self.__cmp(other)
  150. return c <= 0
  151. def __gt__(self, other):
  152. c = self.__cmp(other)
  153. return c > 0
  154. def __ge__(self, other):
  155. c = self.__cmp(other)
  156. return c >= 0
  157. def _implements_name(ob):
  158. # Return the __name__ attribute to be used by its __implemented__
  159. # property.
  160. # This must be stable for the "same" object across processes
  161. # because it is used for sorting. It needn't be unique, though, in cases
  162. # like nested classes named Foo created by different functions, because
  163. # equality and hashing is still based on identity.
  164. # It might be nice to use __qualname__ on Python 3, but that would produce
  165. # different values between Py2 and Py3.
  166. return (getattr(ob, '__module__', '?') or '?') + \
  167. '.' + (getattr(ob, '__name__', '?') or '?')
  168. def implementedByFallback(cls):
  169. """Return the interfaces implemented for a class' instances
  170. The value returned is an IDeclaration.
  171. """
  172. try:
  173. spec = cls.__dict__.get('__implemented__')
  174. except AttributeError:
  175. # we can't get the class dict. This is probably due to a
  176. # security proxy. If this is the case, then probably no
  177. # descriptor was installed for the class.
  178. # We don't want to depend directly on zope.security in
  179. # zope.interface, but we'll try to make reasonable
  180. # accommodations in an indirect way.
  181. # We'll check to see if there's an implements:
  182. spec = getattr(cls, '__implemented__', None)
  183. if spec is None:
  184. # There's no spec stred in the class. Maybe its a builtin:
  185. spec = BuiltinImplementationSpecifications.get(cls)
  186. if spec is not None:
  187. return spec
  188. return _empty
  189. if spec.__class__ == Implements:
  190. # we defaulted to _empty or there was a spec. Good enough.
  191. # Return it.
  192. return spec
  193. # TODO: need old style __implements__ compatibility?
  194. # Hm, there's an __implemented__, but it's not a spec. Must be
  195. # an old-style declaration. Just compute a spec for it
  196. return Declaration(*_normalizeargs((spec, )))
  197. if isinstance(spec, Implements):
  198. return spec
  199. if spec is None:
  200. spec = BuiltinImplementationSpecifications.get(cls)
  201. if spec is not None:
  202. return spec
  203. # TODO: need old style __implements__ compatibility?
  204. spec_name = _implements_name(cls)
  205. if spec is not None:
  206. # old-style __implemented__ = foo declaration
  207. spec = (spec, ) # tuplefy, as it might be just an int
  208. spec = Implements.named(spec_name, *_normalizeargs(spec))
  209. spec.inherit = None # old-style implies no inherit
  210. del cls.__implemented__ # get rid of the old-style declaration
  211. else:
  212. try:
  213. bases = cls.__bases__
  214. except AttributeError:
  215. if not callable(cls):
  216. raise TypeError("ImplementedBy called for non-factory", cls)
  217. bases = ()
  218. spec = Implements.named(spec_name, *[implementedBy(c) for c in bases])
  219. spec.inherit = cls
  220. try:
  221. cls.__implemented__ = spec
  222. if not hasattr(cls, '__providedBy__'):
  223. cls.__providedBy__ = objectSpecificationDescriptor
  224. if (isinstance(cls, DescriptorAwareMetaClasses)
  225. and
  226. '__provides__' not in cls.__dict__):
  227. # Make sure we get a __provides__ descriptor
  228. cls.__provides__ = ClassProvides(
  229. cls,
  230. getattr(cls, '__class__', type(cls)),
  231. )
  232. except TypeError:
  233. if not isinstance(cls, type):
  234. raise TypeError("ImplementedBy called for non-type", cls)
  235. BuiltinImplementationSpecifications[cls] = spec
  236. return spec
  237. implementedBy = implementedByFallback
  238. def classImplementsOnly(cls, *interfaces):
  239. """Declare the only interfaces implemented by instances of a class
  240. The arguments after the class are one or more interfaces or interface
  241. specifications (``IDeclaration`` objects).
  242. The interfaces given (including the interfaces in the specifications)
  243. replace any previous declarations.
  244. """
  245. spec = implementedBy(cls)
  246. spec.declared = ()
  247. spec.inherit = None
  248. classImplements(cls, *interfaces)
  249. def classImplements(cls, *interfaces):
  250. """Declare additional interfaces implemented for instances of a class
  251. The arguments after the class are one or more interfaces or
  252. interface specifications (``IDeclaration`` objects).
  253. The interfaces given (including the interfaces in the specifications)
  254. are added to any interfaces previously declared.
  255. """
  256. spec = implementedBy(cls)
  257. spec.declared += tuple(_normalizeargs(interfaces))
  258. # compute the bases
  259. bases = []
  260. seen = {}
  261. for b in spec.declared:
  262. if b not in seen:
  263. seen[b] = 1
  264. bases.append(b)
  265. if spec.inherit is not None:
  266. for c in spec.inherit.__bases__:
  267. b = implementedBy(c)
  268. if b not in seen:
  269. seen[b] = 1
  270. bases.append(b)
  271. spec.__bases__ = tuple(bases)
  272. def _implements_advice(cls):
  273. interfaces, classImplements = cls.__dict__['__implements_advice_data__']
  274. del cls.__implements_advice_data__
  275. classImplements(cls, *interfaces)
  276. return cls
  277. class implementer:
  278. """Declare the interfaces implemented by instances of a class.
  279. This function is called as a class decorator.
  280. The arguments are one or more interfaces or interface
  281. specifications (IDeclaration objects).
  282. The interfaces given (including the interfaces in the
  283. specifications) are added to any interfaces previously
  284. declared.
  285. Previous declarations include declarations for base classes
  286. unless implementsOnly was used.
  287. This function is provided for convenience. It provides a more
  288. convenient way to call classImplements. For example::
  289. @implementer(I1)
  290. class C(object):
  291. pass
  292. is equivalent to calling::
  293. classImplements(C, I1)
  294. after the class has been created.
  295. """
  296. def __init__(self, *interfaces):
  297. self.interfaces = interfaces
  298. def __call__(self, ob):
  299. if isinstance(ob, DescriptorAwareMetaClasses):
  300. classImplements(ob, *self.interfaces)
  301. return ob
  302. spec_name = _implements_name(ob)
  303. spec = Implements.named(spec_name, *self.interfaces)
  304. try:
  305. ob.__implemented__ = spec
  306. except AttributeError:
  307. raise TypeError("Can't declare implements", ob)
  308. return ob
  309. class implementer_only:
  310. """Declare the only interfaces implemented by instances of a class
  311. This function is called as a class decorator.
  312. The arguments are one or more interfaces or interface
  313. specifications (IDeclaration objects).
  314. Previous declarations including declarations for base classes
  315. are overridden.
  316. This function is provided for convenience. It provides a more
  317. convenient way to call classImplementsOnly. For example::
  318. @implementer_only(I1)
  319. class C(object): pass
  320. is equivalent to calling::
  321. classImplementsOnly(I1)
  322. after the class has been created.
  323. """
  324. def __init__(self, *interfaces):
  325. self.interfaces = interfaces
  326. def __call__(self, ob):
  327. if isinstance(ob, (FunctionType, MethodType)):
  328. # XXX Does this decorator make sense for anything but classes?
  329. # I don't think so. There can be no inheritance of interfaces
  330. # on a method pr function....
  331. raise ValueError('The implementer_only decorator is not '
  332. 'supported for methods or functions.')
  333. else:
  334. # Assume it's a class:
  335. classImplementsOnly(ob, *self.interfaces)
  336. return ob
  337. def _implements(name, interfaces, classImplements):
  338. # This entire approach is invalid under Py3K. Don't even try to fix
  339. # the coverage for this block there. :(
  340. frame = sys._getframe(2)
  341. locals = frame.f_locals
  342. # Try to make sure we were called from a class def. In 2.2.0 we can't
  343. # check for __module__ since it doesn't seem to be added to the locals
  344. # until later on.
  345. if locals is frame.f_globals or '__module__' not in locals:
  346. raise TypeError(name+" can be used only from a class definition.")
  347. if '__implements_advice_data__' in locals:
  348. raise TypeError(name+" can be used only once in a class definition.")
  349. locals['__implements_advice_data__'] = interfaces, classImplements
  350. addClassAdvisor(_implements_advice, depth=3)
  351. def implements(*interfaces):
  352. """Declare interfaces implemented by instances of a class
  353. This function is called in a class definition.
  354. The arguments are one or more interfaces or interface
  355. specifications (IDeclaration objects).
  356. The interfaces given (including the interfaces in the
  357. specifications) are added to any interfaces previously
  358. declared.
  359. Previous declarations include declarations for base classes
  360. unless implementsOnly was used.
  361. This function is provided for convenience. It provides a more
  362. convenient way to call classImplements. For example::
  363. implements(I1)
  364. is equivalent to calling::
  365. classImplements(C, I1)
  366. after the class has been created.
  367. """
  368. # This entire approach is invalid under Py3K. Don't even try to fix
  369. # the coverage for this block there. :(
  370. if PYTHON3:
  371. raise TypeError(_ADVICE_ERROR % 'implementer')
  372. _implements("implements", interfaces, classImplements)
  373. def implementsOnly(*interfaces):
  374. """Declare the only interfaces implemented by instances of a class
  375. This function is called in a class definition.
  376. The arguments are one or more interfaces or interface
  377. specifications (IDeclaration objects).
  378. Previous declarations including declarations for base classes
  379. are overridden.
  380. This function is provided for convenience. It provides a more
  381. convenient way to call classImplementsOnly. For example::
  382. implementsOnly(I1)
  383. is equivalent to calling::
  384. classImplementsOnly(I1)
  385. after the class has been created.
  386. """
  387. # This entire approach is invalid under Py3K. Don't even try to fix
  388. # the coverage for this block there. :(
  389. if PYTHON3:
  390. raise TypeError(_ADVICE_ERROR % 'implementer_only')
  391. _implements("implementsOnly", interfaces, classImplementsOnly)
  392. ##############################################################################
  393. #
  394. # Instance declarations
  395. class Provides(Declaration): # Really named ProvidesClass
  396. """Implement __provides__, the instance-specific specification
  397. When an object is pickled, we pickle the interfaces that it implements.
  398. """
  399. def __init__(self, cls, *interfaces):
  400. self.__args = (cls, ) + interfaces
  401. self._cls = cls
  402. Declaration.__init__(self, *(interfaces + (implementedBy(cls), )))
  403. def __reduce__(self):
  404. return Provides, self.__args
  405. __module__ = 'zope.interface'
  406. def __get__(self, inst, cls):
  407. """Make sure that a class __provides__ doesn't leak to an instance
  408. """
  409. if inst is None and cls is self._cls:
  410. # We were accessed through a class, so we are the class'
  411. # provides spec. Just return this object, but only if we are
  412. # being called on the same class that we were defined for:
  413. return self
  414. raise AttributeError('__provides__')
  415. ProvidesClass = Provides
  416. # Registry of instance declarations
  417. # This is a memory optimization to allow objects to share specifications.
  418. InstanceDeclarations = weakref.WeakValueDictionary()
  419. def Provides(*interfaces):
  420. """Cache instance declarations
  421. Instance declarations are shared among instances that have the same
  422. declaration. The declarations are cached in a weak value dictionary.
  423. """
  424. spec = InstanceDeclarations.get(interfaces)
  425. if spec is None:
  426. spec = ProvidesClass(*interfaces)
  427. InstanceDeclarations[interfaces] = spec
  428. return spec
  429. Provides.__safe_for_unpickling__ = True
  430. def directlyProvides(object, *interfaces):
  431. """Declare interfaces declared directly for an object
  432. The arguments after the object are one or more interfaces or interface
  433. specifications (``IDeclaration`` objects).
  434. The interfaces given (including the interfaces in the specifications)
  435. replace interfaces previously declared for the object.
  436. """
  437. cls = getattr(object, '__class__', None)
  438. if cls is not None and getattr(cls, '__class__', None) is cls:
  439. # It's a meta class (well, at least it it could be an extension class)
  440. # Note that we can't get here from Py3k tests: there is no normal
  441. # class which isn't descriptor aware.
  442. if not isinstance(object,
  443. DescriptorAwareMetaClasses):
  444. raise TypeError("Attempt to make an interface declaration on a "
  445. "non-descriptor-aware class")
  446. interfaces = _normalizeargs(interfaces)
  447. if cls is None:
  448. cls = type(object)
  449. issub = False
  450. for damc in DescriptorAwareMetaClasses:
  451. if issubclass(cls, damc):
  452. issub = True
  453. break
  454. if issub:
  455. # we have a class or type. We'll use a special descriptor
  456. # that provides some extra caching
  457. object.__provides__ = ClassProvides(object, cls, *interfaces)
  458. else:
  459. object.__provides__ = Provides(cls, *interfaces)
  460. def alsoProvides(object, *interfaces):
  461. """Declare interfaces declared directly for an object
  462. The arguments after the object are one or more interfaces or interface
  463. specifications (``IDeclaration`` objects).
  464. The interfaces given (including the interfaces in the specifications) are
  465. added to the interfaces previously declared for the object.
  466. """
  467. directlyProvides(object, directlyProvidedBy(object), *interfaces)
  468. def noLongerProvides(object, interface):
  469. """ Removes a directly provided interface from an object.
  470. """
  471. directlyProvides(object, directlyProvidedBy(object) - interface)
  472. if interface.providedBy(object):
  473. raise ValueError("Can only remove directly provided interfaces.")
  474. class ClassProvidesBaseFallback(object):
  475. def __get__(self, inst, cls):
  476. if cls is self._cls:
  477. # We only work if called on the class we were defined for
  478. if inst is None:
  479. # We were accessed through a class, so we are the class'
  480. # provides spec. Just return this object as is:
  481. return self
  482. return self._implements
  483. raise AttributeError('__provides__')
  484. ClassProvidesBasePy = ClassProvidesBaseFallback # BBB
  485. ClassProvidesBase = ClassProvidesBaseFallback
  486. # Try to get C base:
  487. try:
  488. import zope.interface._zope_interface_coptimizations
  489. except ImportError:
  490. pass
  491. else:
  492. from zope.interface._zope_interface_coptimizations import ClassProvidesBase
  493. class ClassProvides(Declaration, ClassProvidesBase):
  494. """Special descriptor for class __provides__
  495. The descriptor caches the implementedBy info, so that
  496. we can get declarations for objects without instance-specific
  497. interfaces a bit quicker.
  498. """
  499. def __init__(self, cls, metacls, *interfaces):
  500. self._cls = cls
  501. self._implements = implementedBy(cls)
  502. self.__args = (cls, metacls, ) + interfaces
  503. Declaration.__init__(self, *(interfaces + (implementedBy(metacls), )))
  504. def __reduce__(self):
  505. return self.__class__, self.__args
  506. # Copy base-class method for speed
  507. __get__ = ClassProvidesBase.__get__
  508. def directlyProvidedBy(object):
  509. """Return the interfaces directly provided by the given object
  510. The value returned is an ``IDeclaration``.
  511. """
  512. provides = getattr(object, "__provides__", None)
  513. if (provides is None # no spec
  514. or
  515. # We might have gotten the implements spec, as an
  516. # optimization. If so, it's like having only one base, that we
  517. # lop off to exclude class-supplied declarations:
  518. isinstance(provides, Implements)
  519. ):
  520. return _empty
  521. # Strip off the class part of the spec:
  522. return Declaration(provides.__bases__[:-1])
  523. def classProvides(*interfaces):
  524. """Declare interfaces provided directly by a class
  525. This function is called in a class definition.
  526. The arguments are one or more interfaces or interface specifications
  527. (``IDeclaration`` objects).
  528. The given interfaces (including the interfaces in the specifications)
  529. are used to create the class's direct-object interface specification.
  530. An error will be raised if the module class has an direct interface
  531. specification. In other words, it is an error to call this function more
  532. than once in a class definition.
  533. Note that the given interfaces have nothing to do with the interfaces
  534. implemented by instances of the class.
  535. This function is provided for convenience. It provides a more convenient
  536. way to call directlyProvides for a class. For example::
  537. classProvides(I1)
  538. is equivalent to calling::
  539. directlyProvides(theclass, I1)
  540. after the class has been created.
  541. """
  542. # This entire approach is invalid under Py3K. Don't even try to fix
  543. # the coverage for this block there. :(
  544. if PYTHON3:
  545. raise TypeError(_ADVICE_ERROR % 'provider')
  546. frame = sys._getframe(1)
  547. locals = frame.f_locals
  548. # Try to make sure we were called from a class def
  549. if (locals is frame.f_globals) or ('__module__' not in locals):
  550. raise TypeError("classProvides can be used only from a "
  551. "class definition.")
  552. if '__provides__' in locals:
  553. raise TypeError(
  554. "classProvides can only be used once in a class definition.")
  555. locals["__provides__"] = _normalizeargs(interfaces)
  556. addClassAdvisor(_classProvides_advice, depth=2)
  557. def _classProvides_advice(cls):
  558. # This entire approach is invalid under Py3K. Don't even try to fix
  559. # the coverage for this block there. :(
  560. interfaces = cls.__dict__['__provides__']
  561. del cls.__provides__
  562. directlyProvides(cls, *interfaces)
  563. return cls
  564. class provider:
  565. """Class decorator version of classProvides"""
  566. def __init__(self, *interfaces):
  567. self.interfaces = interfaces
  568. def __call__(self, ob):
  569. directlyProvides(ob, *self.interfaces)
  570. return ob
  571. def moduleProvides(*interfaces):
  572. """Declare interfaces provided by a module
  573. This function is used in a module definition.
  574. The arguments are one or more interfaces or interface specifications
  575. (``IDeclaration`` objects).
  576. The given interfaces (including the interfaces in the specifications) are
  577. used to create the module's direct-object interface specification. An
  578. error will be raised if the module already has an interface specification.
  579. In other words, it is an error to call this function more than once in a
  580. module definition.
  581. This function is provided for convenience. It provides a more convenient
  582. way to call directlyProvides. For example::
  583. moduleImplements(I1)
  584. is equivalent to::
  585. directlyProvides(sys.modules[__name__], I1)
  586. """
  587. frame = sys._getframe(1)
  588. locals = frame.f_locals
  589. # Try to make sure we were called from a class def
  590. if (locals is not frame.f_globals) or ('__name__' not in locals):
  591. raise TypeError(
  592. "moduleProvides can only be used from a module definition.")
  593. if '__provides__' in locals:
  594. raise TypeError(
  595. "moduleProvides can only be used once in a module definition.")
  596. locals["__provides__"] = Provides(ModuleType,
  597. *_normalizeargs(interfaces))
  598. ##############################################################################
  599. #
  600. # Declaration querying support
  601. # XXX: is this a fossil? Nobody calls it, no unit tests exercise it, no
  602. # doctests import it, and the package __init__ doesn't import it.
  603. def ObjectSpecification(direct, cls):
  604. """Provide object specifications
  605. These combine information for the object and for it's classes.
  606. """
  607. return Provides(cls, direct) # pragma: no cover fossil
  608. def getObjectSpecificationFallback(ob):
  609. provides = getattr(ob, '__provides__', None)
  610. if provides is not None:
  611. if isinstance(provides, SpecificationBase):
  612. return provides
  613. try:
  614. cls = ob.__class__
  615. except AttributeError:
  616. # We can't get the class, so just consider provides
  617. return _empty
  618. return implementedBy(cls)
  619. getObjectSpecification = getObjectSpecificationFallback
  620. def providedByFallback(ob):
  621. # Here we have either a special object, an old-style declaration
  622. # or a descriptor
  623. # Try to get __providedBy__
  624. try:
  625. r = ob.__providedBy__
  626. except AttributeError:
  627. # Not set yet. Fall back to lower-level thing that computes it
  628. return getObjectSpecification(ob)
  629. try:
  630. # We might have gotten a descriptor from an instance of a
  631. # class (like an ExtensionClass) that doesn't support
  632. # descriptors. We'll make sure we got one by trying to get
  633. # the only attribute, which all specs have.
  634. r.extends
  635. except AttributeError:
  636. # The object's class doesn't understand descriptors.
  637. # Sigh. We need to get an object descriptor, but we have to be
  638. # careful. We want to use the instance's __provides__, if
  639. # there is one, but only if it didn't come from the class.
  640. try:
  641. r = ob.__provides__
  642. except AttributeError:
  643. # No __provides__, so just fall back to implementedBy
  644. return implementedBy(ob.__class__)
  645. # We need to make sure we got the __provides__ from the
  646. # instance. We'll do this by making sure we don't get the same
  647. # thing from the class:
  648. try:
  649. cp = ob.__class__.__provides__
  650. except AttributeError:
  651. # The ob doesn't have a class or the class has no
  652. # provides, assume we're done:
  653. return r
  654. if r is cp:
  655. # Oops, we got the provides from the class. This means
  656. # the object doesn't have it's own. We should use implementedBy
  657. return implementedBy(ob.__class__)
  658. return r
  659. providedBy = providedByFallback
  660. class ObjectSpecificationDescriptorFallback(object):
  661. """Implement the `__providedBy__` attribute
  662. The `__providedBy__` attribute computes the interfaces peovided by
  663. an object.
  664. """
  665. def __get__(self, inst, cls):
  666. """Get an object specification for an object
  667. """
  668. if inst is None:
  669. return getObjectSpecification(cls)
  670. provides = getattr(inst, '__provides__', None)
  671. if provides is not None:
  672. return provides
  673. return implementedBy(cls)
  674. ObjectSpecificationDescriptor = ObjectSpecificationDescriptorFallback
  675. ##############################################################################
  676. def _normalizeargs(sequence, output = None):
  677. """Normalize declaration arguments
  678. Normalization arguments might contain Declarions, tuples, or single
  679. interfaces.
  680. Anything but individial interfaces or implements specs will be expanded.
  681. """
  682. if output is None:
  683. output = []
  684. cls = sequence.__class__
  685. if InterfaceClass in cls.__mro__ or Implements in cls.__mro__:
  686. output.append(sequence)
  687. else:
  688. for v in sequence:
  689. _normalizeargs(v, output)
  690. return output
  691. _empty = Declaration()
  692. try:
  693. import zope.interface._zope_interface_coptimizations
  694. except ImportError:
  695. pass
  696. else:
  697. from zope.interface._zope_interface_coptimizations import implementedBy
  698. from zope.interface._zope_interface_coptimizations import providedBy
  699. from zope.interface._zope_interface_coptimizations import (
  700. getObjectSpecification)
  701. from zope.interface._zope_interface_coptimizations import (
  702. ObjectSpecificationDescriptor)
  703. objectSpecificationDescriptor = ObjectSpecificationDescriptor()