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