Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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 """ 

119 Add two specifications or a specification and an interface 

120 and produce a new declaration. 

121 

122 .. versionchanged:: 5.4.0 

123 Now tries to preserve a consistent resolution order. Interfaces 

124 being added to this object are added to the front of the resulting resolution 

125 order if they already extend an interface in this object. Previously, 

126 they were always added to the end of the order, which easily resulted in 

127 invalid orders. 

128 """ 

129 before = [] 

130 result = list(self.interfaces()) 

131 seen = set(result) 

132 for i in other.interfaces(): 

133 if i in seen: 

134 continue 

135 seen.add(i) 

136 if any(i.extends(x) for x in result): 

137 # It already extends us, e.g., is a subclass, 

138 # so it needs to go at the front of the RO. 

139 before.append(i) 

140 else: 

141 result.append(i) 

142 return Declaration(*(before + result)) 

143 

144 # XXX: Is __radd__ needed? No tests break if it's removed. 

145 # If it is needed, does it need to handle the C3 ordering differently? 

146 # I (JAM) don't *think* it does. 

147 __radd__ = __add__ 

148 

149 @staticmethod 

150 def _add_interfaces_to_cls(interfaces, cls): 

151 # Strip redundant interfaces already provided 

152 # by the cls so we don't produce invalid 

153 # resolution orders. 

154 implemented_by_cls = implementedBy(cls) 

155 interfaces = tuple([ 

156 iface 

157 for iface in interfaces 

158 if not implemented_by_cls.isOrExtends(iface) 

159 ]) 

160 return interfaces + (implemented_by_cls,) 

161 

162 @staticmethod 

163 def _argument_names_for_repr(interfaces): 

164 # These don't actually have to be interfaces, they could be other 

165 # Specification objects like Implements. Also, the first 

166 # one is typically/nominally the cls. 

167 ordered_names = [] 

168 names = set() 

169 for iface in interfaces: 

170 duplicate_transform = repr 

171 if isinstance(iface, InterfaceClass): 

172 # Special case to get 'foo.bar.IFace' 

173 # instead of '<InterfaceClass foo.bar.IFace>' 

174 this_name = iface.__name__ 

175 duplicate_transform = str 

176 elif isinstance(iface, type): 

177 # Likewise for types. (Ignoring legacy old-style 

178 # classes.) 

179 this_name = iface.__name__ 

180 duplicate_transform = _implements_name 

181 elif (isinstance(iface, Implements) 

182 and not iface.declared 

183 and iface.inherit in interfaces): 

184 # If nothing is declared, there's no need to even print this; 

185 # it would just show as ``classImplements(Class)``, and the 

186 # ``Class`` has typically already. 

187 continue 

188 else: 

189 this_name = repr(iface) 

190 

191 already_seen = this_name in names 

192 names.add(this_name) 

193 if already_seen: 

194 this_name = duplicate_transform(iface) 

195 

196 ordered_names.append(this_name) 

197 return ', '.join(ordered_names) 

198 

199 

200class _ImmutableDeclaration(Declaration): 

201 # A Declaration that is immutable. Used as a singleton to 

202 # return empty answers for things like ``implementedBy``. 

203 # We have to define the actual singleton after normalizeargs 

204 # is defined, and that in turn is defined after InterfaceClass and 

205 # Implements. 

206 

207 __slots__ = () 

208 

209 __instance = None 

210 

211 def __new__(cls): 

212 if _ImmutableDeclaration.__instance is None: 

213 _ImmutableDeclaration.__instance = object.__new__(cls) 

214 return _ImmutableDeclaration.__instance 

215 

216 def __reduce__(self): 

217 return "_empty" 

218 

219 @property 

220 def __bases__(self): 

221 return () 

222 

223 @__bases__.setter 

224 def __bases__(self, new_bases): 

225 # We expect the superclass constructor to set ``self.__bases__ = ()``. 

226 # Rather than attempt to special case that in the constructor and allow 

227 # setting __bases__ only at that time, it's easier to just allow setting 

228 # the empty tuple at any time. That makes ``x.__bases__ = x.__bases__`` a nice 

229 # no-op too. (Skipping the superclass constructor altogether is a recipe 

230 # for maintenance headaches.) 

231 if new_bases != (): 

232 raise TypeError("Cannot set non-empty bases on shared empty Declaration.") 

233 

234 # As the immutable empty declaration, we cannot be changed. 

235 # This means there's no logical reason for us to have dependents 

236 # or subscriptions: we'll never notify them. So there's no need for 

237 # us to keep track of any of that. 

238 @property 

239 def dependents(self): 

240 return {} 

241 

242 changed = subscribe = unsubscribe = lambda self, _ignored: None 

243 

244 def interfaces(self): 

245 # An empty iterator 

246 return iter(()) 

247 

248 def extends(self, interface, strict=True): 

249 return interface is self._ROOT 

250 

251 def get(self, name, default=None): 

252 return default 

253 

254 def weakref(self, callback=None): 

255 # We're a singleton, we never go away. So there's no need to return 

256 # distinct weakref objects here; their callbacks will never 

257 # be called. Instead, we only need to return a callable that 

258 # returns ourself. The easiest one is to return _ImmutableDeclaration 

259 # itself; testing on Python 3.8 shows that's faster than a function that 

260 # returns _empty. (Remember, one goal is to avoid allocating any 

261 # object, and that includes a method.) 

262 return _ImmutableDeclaration 

263 

264 @property 

265 def _v_attrs(self): 

266 # _v_attrs is not a public, documented property, but some client 

267 # code uses it anyway as a convenient place to cache things. To keep 

268 # the empty declaration truly immutable, we must ignore that. That includes 

269 # ignoring assignments as well. 

270 return {} 

271 

272 @_v_attrs.setter 

273 def _v_attrs(self, new_attrs): 

274 pass 

275 

276 

277############################################################################## 

278# 

279# Implementation specifications 

280# 

281# These specify interfaces implemented by instances of classes 

282 

283class Implements(NameAndModuleComparisonMixin, 

284 Declaration): 

285 # Inherit from NameAndModuleComparisonMixin to be 

286 # mutually comparable with InterfaceClass objects. 

287 # (The two must be mutually comparable to be able to work in e.g., BTrees.) 

288 # Instances of this class generally don't have a __module__ other than 

289 # `zope.interface.declarations`, whereas they *do* have a __name__ that is the 

290 # fully qualified name of the object they are representing. 

291 

292 # Note, though, that equality and hashing are still identity based. This 

293 # accounts for things like nested objects that have the same name (typically 

294 # only in tests) and is consistent with pickling. As far as comparisons to InterfaceClass 

295 # goes, we'll never have equal name and module to those, so we're still consistent there. 

296 # Instances of this class are essentially intended to be unique and are 

297 # heavily cached (note how our __reduce__ handles this) so having identity 

298 # based hash and eq should also work. 

299 

300 # We want equality and hashing to be based on identity. However, we can't actually 

301 # implement __eq__/__ne__ to do this because sometimes we get wrapped in a proxy. 

302 # We need to let the proxy types implement these methods so they can handle unwrapping 

303 # and then rely on: (1) the interpreter automatically changing `implements == proxy` into 

304 # `proxy == implements` (which will call proxy.__eq__ to do the unwrapping) and then 

305 # (2) the default equality and hashing semantics being identity based. 

306 

307 # class whose specification should be used as additional base 

308 inherit = None 

309 

310 # interfaces actually declared for a class 

311 declared = () 

312 

313 # Weak cache of {class: <implements>} for super objects. 

314 # Created on demand. These are rare, as of 5.0 anyway. Using a class 

315 # level default doesn't take space in instances. Using _v_attrs would be 

316 # another place to store this without taking space unless needed. 

317 _super_cache = None 

318 

319 __name__ = '?' 

320 

321 @classmethod 

322 def named(cls, name, *bases): 

323 # Implementation method: Produce an Implements interface with 

324 # a fully fleshed out __name__ before calling the constructor, which 

325 # sets bases to the given interfaces and which may pass this object to 

326 # other objects (e.g., to adjust dependents). If they're sorting or comparing 

327 # by name, this needs to be set. 

328 inst = cls.__new__(cls) 

329 inst.__name__ = name 

330 inst.__init__(*bases) 

331 return inst 

332 

333 def changed(self, originally_changed): 

334 try: 

335 del self._super_cache 

336 except AttributeError: 

337 pass 

338 return super(Implements, self).changed(originally_changed) 

339 

340 def __repr__(self): 

341 if self.inherit: 

342 name = getattr(self.inherit, '__name__', None) or _implements_name(self.inherit) 

343 else: 

344 name = self.__name__ 

345 declared_names = self._argument_names_for_repr(self.declared) 

346 if declared_names: 

347 declared_names = ', ' + declared_names 

348 return 'classImplements(%s%s)' % (name, declared_names) 

349 

350 def __reduce__(self): 

351 return implementedBy, (self.inherit, ) 

352 

353 

354def _implements_name(ob): 

355 # Return the __name__ attribute to be used by its __implemented__ 

356 # property. 

357 # This must be stable for the "same" object across processes 

358 # because it is used for sorting. It needn't be unique, though, in cases 

359 # like nested classes named Foo created by different functions, because 

360 # equality and hashing is still based on identity. 

361 # It might be nice to use __qualname__ on Python 3, but that would produce 

362 # different values between Py2 and Py3. 

363 return (getattr(ob, '__module__', '?') or '?') + \ 

364 '.' + (getattr(ob, '__name__', '?') or '?') 

365 

366 

367def _implementedBy_super(sup): 

368 # TODO: This is now simple enough we could probably implement 

369 # in C if needed. 

370 

371 # If the class MRO is strictly linear, we could just 

372 # follow the normal algorithm for the next class in the 

373 # search order (e.g., just return 

374 # ``implemented_by_next``). But when diamond inheritance 

375 # or mixins + interface declarations are present, we have 

376 # to consider the whole MRO and compute a new Implements 

377 # that excludes the classes being skipped over but 

378 # includes everything else. 

379 implemented_by_self = implementedBy(sup.__self_class__) 

380 cache = implemented_by_self._super_cache # pylint:disable=protected-access 

381 if cache is None: 

382 cache = implemented_by_self._super_cache = weakref.WeakKeyDictionary() 

383 

384 key = sup.__thisclass__ 

385 try: 

386 return cache[key] 

387 except KeyError: 

388 pass 

389 

390 next_cls = _next_super_class(sup) 

391 # For ``implementedBy(cls)``: 

392 # .__bases__ is .declared + [implementedBy(b) for b in cls.__bases__] 

393 # .inherit is cls 

394 

395 implemented_by_next = implementedBy(next_cls) 

396 mro = sup.__self_class__.__mro__ 

397 ix_next_cls = mro.index(next_cls) 

398 classes_to_keep = mro[ix_next_cls:] 

399 new_bases = [implementedBy(c) for c in classes_to_keep] 

400 

401 new = Implements.named( 

402 implemented_by_self.__name__ + ':' + implemented_by_next.__name__, 

403 *new_bases 

404 ) 

405 new.inherit = implemented_by_next.inherit 

406 new.declared = implemented_by_next.declared 

407 # I don't *think* that new needs to subscribe to ``implemented_by_self``; 

408 # it auto-subscribed to its bases, and that should be good enough. 

409 cache[key] = new 

410 

411 return new 

412 

413 

414@_use_c_impl 

415def implementedBy(cls): # pylint:disable=too-many-return-statements,too-many-branches 

416 """Return the interfaces implemented for a class' instances 

417 

418 The value returned is an `~zope.interface.interfaces.IDeclaration`. 

419 """ 

420 try: 

421 if isinstance(cls, super): 

422 # Yes, this needs to be inside the try: block. Some objects 

423 # like security proxies even break isinstance. 

424 return _implementedBy_super(cls) 

425 

426 spec = cls.__dict__.get('__implemented__') 

427 except AttributeError: 

428 

429 # we can't get the class dict. This is probably due to a 

430 # security proxy. If this is the case, then probably no 

431 # descriptor was installed for the class. 

432 

433 # We don't want to depend directly on zope.security in 

434 # zope.interface, but we'll try to make reasonable 

435 # accommodations in an indirect way. 

436 

437 # We'll check to see if there's an implements: 

438 

439 spec = getattr(cls, '__implemented__', None) 

440 if spec is None: 

441 # There's no spec stred in the class. Maybe its a builtin: 

442 spec = BuiltinImplementationSpecifications.get(cls) 

443 if spec is not None: 

444 return spec 

445 return _empty 

446 

447 if spec.__class__ == Implements: 

448 # we defaulted to _empty or there was a spec. Good enough. 

449 # Return it. 

450 return spec 

451 

452 # TODO: need old style __implements__ compatibility? 

453 # Hm, there's an __implemented__, but it's not a spec. Must be 

454 # an old-style declaration. Just compute a spec for it 

455 return Declaration(*_normalizeargs((spec, ))) 

456 

457 if isinstance(spec, Implements): 

458 return spec 

459 

460 if spec is None: 

461 spec = BuiltinImplementationSpecifications.get(cls) 

462 if spec is not None: 

463 return spec 

464 

465 # TODO: need old style __implements__ compatibility? 

466 spec_name = _implements_name(cls) 

467 if spec is not None: 

468 # old-style __implemented__ = foo declaration 

469 spec = (spec, ) # tuplefy, as it might be just an int 

470 spec = Implements.named(spec_name, *_normalizeargs(spec)) 

471 spec.inherit = None # old-style implies no inherit 

472 del cls.__implemented__ # get rid of the old-style declaration 

473 else: 

474 try: 

475 bases = cls.__bases__ 

476 except AttributeError: 

477 if not callable(cls): 

478 raise TypeError("ImplementedBy called for non-factory", cls) 

479 bases = () 

480 

481 spec = Implements.named(spec_name, *[implementedBy(c) for c in bases]) 

482 spec.inherit = cls 

483 

484 try: 

485 cls.__implemented__ = spec 

486 if not hasattr(cls, '__providedBy__'): 

487 cls.__providedBy__ = objectSpecificationDescriptor 

488 

489 if (isinstance(cls, DescriptorAwareMetaClasses) 

490 and '__provides__' not in cls.__dict__): 

491 # Make sure we get a __provides__ descriptor 

492 cls.__provides__ = ClassProvides( 

493 cls, 

494 getattr(cls, '__class__', type(cls)), 

495 ) 

496 

497 except TypeError: 

498 if not isinstance(cls, type): 

499 raise TypeError("ImplementedBy called for non-type", cls) 

500 BuiltinImplementationSpecifications[cls] = spec 

501 

502 return spec 

503 

504 

505def classImplementsOnly(cls, *interfaces): 

506 """ 

507 Declare the only interfaces implemented by instances of a class 

508 

509 The arguments after the class are one or more interfaces or interface 

510 specifications (`~zope.interface.interfaces.IDeclaration` objects). 

511 

512 The interfaces given (including the interfaces in the specifications) 

513 replace any previous declarations, *including* inherited definitions. If you 

514 wish to preserve inherited declarations, you can pass ``implementedBy(cls)`` 

515 in *interfaces*. This can be used to alter the interface resolution order. 

516 """ 

517 spec = implementedBy(cls) 

518 # Clear out everything inherited. It's important to 

519 # also clear the bases right now so that we don't improperly discard 

520 # interfaces that are already implemented by *old* bases that we're 

521 # about to get rid of. 

522 spec.declared = () 

523 spec.inherit = None 

524 spec.__bases__ = () 

525 _classImplements_ordered(spec, interfaces, ()) 

526 

527 

528def classImplements(cls, *interfaces): 

529 """ 

530 Declare additional interfaces implemented for instances of a class 

531 

532 The arguments after the class are one or more interfaces or 

533 interface specifications (`~zope.interface.interfaces.IDeclaration` objects). 

534 

535 The interfaces given (including the interfaces in the specifications) 

536 are added to any interfaces previously declared. An effort is made to 

537 keep a consistent C3 resolution order, but this cannot be guaranteed. 

538 

539 .. versionchanged:: 5.0.0 

540 Each individual interface in *interfaces* may be added to either the 

541 beginning or end of the list of interfaces declared for *cls*, 

542 based on inheritance, in order to try to maintain a consistent 

543 resolution order. Previously, all interfaces were added to the end. 

544 .. versionchanged:: 5.1.0 

545 If *cls* is already declared to implement an interface (or derived interface) 

546 in *interfaces* through inheritance, the interface is ignored. Previously, it 

547 would redundantly be made direct base of *cls*, which often produced inconsistent 

548 interface resolution orders. Now, the order will be consistent, but may change. 

549 Also, if the ``__bases__`` of the *cls* are later changed, the *cls* will no 

550 longer be considered to implement such an interface (changing the ``__bases__`` of *cls* 

551 has never been supported). 

552 """ 

553 spec = implementedBy(cls) 

554 interfaces = tuple(_normalizeargs(interfaces)) 

555 

556 before = [] 

557 after = [] 

558 

559 # Take steps to try to avoid producing an invalid resolution 

560 # order, while still allowing for BWC (in the past, we always 

561 # appended) 

562 for iface in interfaces: 

563 for b in spec.declared: 

564 if iface.extends(b): 

565 before.append(iface) 

566 break 

567 else: 

568 after.append(iface) 

569 _classImplements_ordered(spec, tuple(before), tuple(after)) 

570 

571 

572def classImplementsFirst(cls, iface): 

573 """ 

574 Declare that instances of *cls* additionally provide *iface*. 

575 

576 The second argument is an interface or interface specification. 

577 It is added as the highest priority (first in the IRO) interface; 

578 no attempt is made to keep a consistent resolution order. 

579 

580 .. versionadded:: 5.0.0 

581 """ 

582 spec = implementedBy(cls) 

583 _classImplements_ordered(spec, (iface,), ()) 

584 

585 

586def _classImplements_ordered(spec, before=(), after=()): 

587 # Elide everything already inherited. 

588 # Except, if it is the root, and we don't already declare anything else 

589 # that would imply it, allow the root through. (TODO: When we disallow non-strict 

590 # IRO, this part of the check can be removed because it's not possible to re-declare 

591 # like that.) 

592 before = [ 

593 x 

594 for x in before 

595 if not spec.isOrExtends(x) or (x is Interface and not spec.declared) 

596 ] 

597 after = [ 

598 x 

599 for x in after 

600 if not spec.isOrExtends(x) or (x is Interface and not spec.declared) 

601 ] 

602 

603 # eliminate duplicates 

604 new_declared = [] 

605 seen = set() 

606 for l in before, spec.declared, after: 

607 for b in l: 

608 if b not in seen: 

609 new_declared.append(b) 

610 seen.add(b) 

611 

612 spec.declared = tuple(new_declared) 

613 

614 # compute the bases 

615 bases = new_declared # guaranteed no dupes 

616 

617 if spec.inherit is not None: 

618 for c in spec.inherit.__bases__: 

619 b = implementedBy(c) 

620 if b not in seen: 

621 seen.add(b) 

622 bases.append(b) 

623 

624 spec.__bases__ = tuple(bases) 

625 

626 

627def _implements_advice(cls): 

628 interfaces, do_classImplements = cls.__dict__['__implements_advice_data__'] 

629 del cls.__implements_advice_data__ 

630 do_classImplements(cls, *interfaces) 

631 return cls 

632 

633 

634class implementer(object): 

635 """ 

636 Declare the interfaces implemented by instances of a class. 

637 

638 This function is called as a class decorator. 

639 

640 The arguments are one or more interfaces or interface 

641 specifications (`~zope.interface.interfaces.IDeclaration` 

642 objects). 

643 

644 The interfaces given (including the interfaces in the 

645 specifications) are added to any interfaces previously declared, 

646 unless the interface is already implemented. 

647 

648 Previous declarations include declarations for base classes unless 

649 implementsOnly was used. 

650 

651 This function is provided for convenience. It provides a more 

652 convenient way to call `classImplements`. For example:: 

653 

654 @implementer(I1) 

655 class C(object): 

656 pass 

657 

658 is equivalent to calling:: 

659 

660 classImplements(C, I1) 

661 

662 after the class has been created. 

663 

664 .. seealso:: `classImplements` 

665 The change history provided there applies to this function too. 

666 """ 

667 __slots__ = ('interfaces',) 

668 

669 def __init__(self, *interfaces): 

670 self.interfaces = interfaces 

671 

672 def __call__(self, ob): 

673 if isinstance(ob, DescriptorAwareMetaClasses): 

674 # This is the common branch for new-style (object) and 

675 # on Python 2 old-style classes. 

676 classImplements(ob, *self.interfaces) 

677 return ob 

678 

679 spec_name = _implements_name(ob) 

680 spec = Implements.named(spec_name, *self.interfaces) 

681 try: 

682 ob.__implemented__ = spec 

683 except AttributeError: 

684 raise TypeError("Can't declare implements", ob) 

685 return ob 

686 

687class implementer_only(object): 

688 """Declare the only interfaces implemented by instances of a class 

689 

690 This function is called as a class decorator. 

691 

692 The arguments are one or more interfaces or interface 

693 specifications (`~zope.interface.interfaces.IDeclaration` objects). 

694 

695 Previous declarations including declarations for base classes 

696 are overridden. 

697 

698 This function is provided for convenience. It provides a more 

699 convenient way to call `classImplementsOnly`. For example:: 

700 

701 @implementer_only(I1) 

702 class C(object): pass 

703 

704 is equivalent to calling:: 

705 

706 classImplementsOnly(I1) 

707 

708 after the class has been created. 

709 """ 

710 

711 def __init__(self, *interfaces): 

712 self.interfaces = interfaces 

713 

714 def __call__(self, ob): 

715 if isinstance(ob, (FunctionType, MethodType)): 

716 # XXX Does this decorator make sense for anything but classes? 

717 # I don't think so. There can be no inheritance of interfaces 

718 # on a method or function.... 

719 raise ValueError('The implementer_only decorator is not ' 

720 'supported for methods or functions.') 

721 

722 # Assume it's a class: 

723 classImplementsOnly(ob, *self.interfaces) 

724 return ob 

725 

726def _implements(name, interfaces, do_classImplements): 

727 # This entire approach is invalid under Py3K. Don't even try to fix 

728 # the coverage for this block there. :( 

729 frame = sys._getframe(2) # pylint:disable=protected-access 

730 locals = frame.f_locals # pylint:disable=redefined-builtin 

731 

732 # Try to make sure we were called from a class def. In 2.2.0 we can't 

733 # check for __module__ since it doesn't seem to be added to the locals 

734 # until later on. 

735 if locals is frame.f_globals or '__module__' not in locals: 

736 raise TypeError(name+" can be used only from a class definition.") 

737 

738 if '__implements_advice_data__' in locals: 

739 raise TypeError(name+" can be used only once in a class definition.") 

740 

741 locals['__implements_advice_data__'] = interfaces, do_classImplements 

742 addClassAdvisor(_implements_advice, depth=3) 

743 

744def implements(*interfaces): 

745 """ 

746 Declare interfaces implemented by instances of a class. 

747 

748 .. deprecated:: 5.0 

749 This only works for Python 2. The `implementer` decorator 

750 is preferred for all versions. 

751 

752 This function is called in a class definition. 

753 

754 The arguments are one or more interfaces or interface 

755 specifications (`~zope.interface.interfaces.IDeclaration` 

756 objects). 

757 

758 The interfaces given (including the interfaces in the 

759 specifications) are added to any interfaces previously declared. 

760 

761 Previous declarations include declarations for base classes unless 

762 `implementsOnly` was used. 

763 

764 This function is provided for convenience. It provides a more 

765 convenient way to call `classImplements`. For example:: 

766 

767 implements(I1) 

768 

769 is equivalent to calling:: 

770 

771 classImplements(C, I1) 

772 

773 after the class has been created. 

774 """ 

775 # This entire approach is invalid under Py3K. Don't even try to fix 

776 # the coverage for this block there. :( 

777 if PYTHON3: 

778 raise TypeError(_ADVICE_ERROR % 'implementer') 

779 _implements("implements", interfaces, classImplements) 

780 

781def implementsOnly(*interfaces): 

782 """Declare the only interfaces implemented by instances of a class 

783 

784 This function is called in a class definition. 

785 

786 The arguments are one or more interfaces or interface 

787 specifications (`~zope.interface.interfaces.IDeclaration` objects). 

788 

789 Previous declarations including declarations for base classes 

790 are overridden. 

791 

792 This function is provided for convenience. It provides a more 

793 convenient way to call `classImplementsOnly`. For example:: 

794 

795 implementsOnly(I1) 

796 

797 is equivalent to calling:: 

798 

799 classImplementsOnly(I1) 

800 

801 after the class has been created. 

802 """ 

803 # This entire approach is invalid under Py3K. Don't even try to fix 

804 # the coverage for this block there. :( 

805 if PYTHON3: 

806 raise TypeError(_ADVICE_ERROR % 'implementer_only') 

807 _implements("implementsOnly", interfaces, classImplementsOnly) 

808 

809############################################################################## 

810# 

811# Instance declarations 

812 

813class Provides(Declaration): # Really named ProvidesClass 

814 """Implement ``__provides__``, the instance-specific specification 

815 

816 When an object is pickled, we pickle the interfaces that it implements. 

817 """ 

818 

819 def __init__(self, cls, *interfaces): 

820 self.__args = (cls, ) + interfaces 

821 self._cls = cls 

822 Declaration.__init__(self, *self._add_interfaces_to_cls(interfaces, cls)) 

823 

824 # Added to by ``moduleProvides``, et al 

825 _v_module_names = () 

826 

827 def __repr__(self): 

828 # The typical way to create instances of this 

829 # object is via calling ``directlyProvides(...)`` or ``alsoProvides()``, 

830 # but that's not the only way. Proxies, for example, 

831 # directly use the ``Provides(...)`` function (which is the 

832 # more generic method, and what we pickle as). We're after the most 

833 # readable, useful repr in the common case, so we use the most 

834 # common name. 

835 # 

836 # We also cooperate with ``moduleProvides`` to attempt to do the 

837 # right thing for that API. See it for details. 

838 function_name = 'directlyProvides' 

839 if self._cls is ModuleType and self._v_module_names: 

840 # See notes in ``moduleProvides``/``directlyProvides`` 

841 providing_on_module = True 

842 interfaces = self.__args[1:] 

843 else: 

844 providing_on_module = False 

845 interfaces = (self._cls,) + self.__bases__ 

846 ordered_names = self._argument_names_for_repr(interfaces) 

847 if providing_on_module: 

848 mod_names = self._v_module_names 

849 if len(mod_names) == 1: 

850 mod_names = "sys.modules[%r]" % mod_names[0] 

851 ordered_names = ( 

852 '%s, ' % (mod_names,) 

853 ) + ordered_names 

854 return "%s(%s)" % ( 

855 function_name, 

856 ordered_names, 

857 ) 

858 

859 def __reduce__(self): 

860 # This reduces to the Provides *function*, not 

861 # this class. 

862 return Provides, self.__args 

863 

864 __module__ = 'zope.interface' 

865 

866 def __get__(self, inst, cls): 

867 """Make sure that a class __provides__ doesn't leak to an instance 

868 """ 

869 if inst is None and cls is self._cls: 

870 # We were accessed through a class, so we are the class' 

871 # provides spec. Just return this object, but only if we are 

872 # being called on the same class that we were defined for: 

873 return self 

874 

875 raise AttributeError('__provides__') 

876 

877ProvidesClass = Provides 

878 

879# Registry of instance declarations 

880# This is a memory optimization to allow objects to share specifications. 

881InstanceDeclarations = weakref.WeakValueDictionary() 

882 

883def Provides(*interfaces): # pylint:disable=function-redefined 

884 """Cache instance declarations 

885 

886 Instance declarations are shared among instances that have the same 

887 declaration. The declarations are cached in a weak value dictionary. 

888 """ 

889 spec = InstanceDeclarations.get(interfaces) 

890 if spec is None: 

891 spec = ProvidesClass(*interfaces) 

892 InstanceDeclarations[interfaces] = spec 

893 

894 return spec 

895 

896Provides.__safe_for_unpickling__ = True 

897 

898 

899def directlyProvides(object, *interfaces): # pylint:disable=redefined-builtin 

900 """Declare interfaces declared directly for an object 

901 

902 The arguments after the object are one or more interfaces or interface 

903 specifications (`~zope.interface.interfaces.IDeclaration` objects). 

904 

905 The interfaces given (including the interfaces in the specifications) 

906 replace interfaces previously declared for the object. 

907 """ 

908 cls = getattr(object, '__class__', None) 

909 if cls is not None and getattr(cls, '__class__', None) is cls: 

910 # It's a meta class (well, at least it it could be an extension class) 

911 # Note that we can't get here from Py3k tests: there is no normal 

912 # class which isn't descriptor aware. 

913 if not isinstance(object, 

914 DescriptorAwareMetaClasses): 

915 raise TypeError("Attempt to make an interface declaration on a " 

916 "non-descriptor-aware class") 

917 

918 interfaces = _normalizeargs(interfaces) 

919 if cls is None: 

920 cls = type(object) 

921 

922 issub = False 

923 for damc in DescriptorAwareMetaClasses: 

924 if issubclass(cls, damc): 

925 issub = True 

926 break 

927 if issub: 

928 # we have a class or type. We'll use a special descriptor 

929 # that provides some extra caching 

930 object.__provides__ = ClassProvides(object, cls, *interfaces) 

931 else: 

932 provides = object.__provides__ = Provides(cls, *interfaces) 

933 # See notes in ``moduleProvides``. 

934 if issubclass(cls, ModuleType) and hasattr(object, '__name__'): 

935 provides._v_module_names += (object.__name__,) 

936 

937 

938 

939def alsoProvides(object, *interfaces): # pylint:disable=redefined-builtin 

940 """Declare interfaces declared directly for an object 

941 

942 The arguments after the object are one or more interfaces or interface 

943 specifications (`~zope.interface.interfaces.IDeclaration` objects). 

944 

945 The interfaces given (including the interfaces in the specifications) are 

946 added to the interfaces previously declared for the object. 

947 """ 

948 directlyProvides(object, directlyProvidedBy(object), *interfaces) 

949 

950 

951def noLongerProvides(object, interface): # pylint:disable=redefined-builtin 

952 """ Removes a directly provided interface from an object. 

953 """ 

954 directlyProvides(object, directlyProvidedBy(object) - interface) 

955 if interface.providedBy(object): 

956 raise ValueError("Can only remove directly provided interfaces.") 

957 

958 

959@_use_c_impl 

960class ClassProvidesBase(SpecificationBase): 

961 

962 __slots__ = ( 

963 '_cls', 

964 '_implements', 

965 ) 

966 

967 def __get__(self, inst, cls): 

968 # member slots are set by subclass 

969 # pylint:disable=no-member 

970 if cls is self._cls: 

971 # We only work if called on the class we were defined for 

972 

973 if inst is None: 

974 # We were accessed through a class, so we are the class' 

975 # provides spec. Just return this object as is: 

976 return self 

977 

978 return self._implements 

979 

980 raise AttributeError('__provides__') 

981 

982 

983class ClassProvides(Declaration, ClassProvidesBase): 

984 """Special descriptor for class ``__provides__`` 

985 

986 The descriptor caches the implementedBy info, so that 

987 we can get declarations for objects without instance-specific 

988 interfaces a bit quicker. 

989 """ 

990 

991 __slots__ = ( 

992 '__args', 

993 ) 

994 

995 def __init__(self, cls, metacls, *interfaces): 

996 self._cls = cls 

997 self._implements = implementedBy(cls) 

998 self.__args = (cls, metacls, ) + interfaces 

999 Declaration.__init__(self, *self._add_interfaces_to_cls(interfaces, metacls)) 

1000 

1001 def __repr__(self): 

1002 # There are two common ways to get instances of this object: 

1003 # The most interesting way is calling ``@provider(..)`` as a decorator 

1004 # of a class; this is the same as calling ``directlyProvides(cls, ...)``. 

1005 # 

1006 # The other way is by default: anything that invokes ``implementedBy(x)`` 

1007 # will wind up putting an instance in ``type(x).__provides__``; this includes 

1008 # the ``@implementer(...)`` decorator. Those instances won't have any 

1009 # interfaces. 

1010 # 

1011 # Thus, as our repr, we go with the ``directlyProvides()`` syntax. 

1012 interfaces = (self._cls, ) + self.__args[2:] 

1013 ordered_names = self._argument_names_for_repr(interfaces) 

1014 return "directlyProvides(%s)" % (ordered_names,) 

1015 

1016 def __reduce__(self): 

1017 return self.__class__, self.__args 

1018 

1019 # Copy base-class method for speed 

1020 __get__ = ClassProvidesBase.__get__ 

1021 

1022 

1023def directlyProvidedBy(object): # pylint:disable=redefined-builtin 

1024 """Return the interfaces directly provided by the given object 

1025 

1026 The value returned is an `~zope.interface.interfaces.IDeclaration`. 

1027 """ 

1028 provides = getattr(object, "__provides__", None) 

1029 if ( 

1030 provides is None # no spec 

1031 # We might have gotten the implements spec, as an 

1032 # optimization. If so, it's like having only one base, that we 

1033 # lop off to exclude class-supplied declarations: 

1034 or isinstance(provides, Implements) 

1035 ): 

1036 return _empty 

1037 

1038 # Strip off the class part of the spec: 

1039 return Declaration(provides.__bases__[:-1]) 

1040 

1041 

1042def classProvides(*interfaces): 

1043 """Declare interfaces provided directly by a class 

1044 

1045 This function is called in a class definition. 

1046 

1047 The arguments are one or more interfaces or interface specifications 

1048 (`~zope.interface.interfaces.IDeclaration` objects). 

1049 

1050 The given interfaces (including the interfaces in the specifications) 

1051 are used to create the class's direct-object interface specification. 

1052 An error will be raised if the module class has an direct interface 

1053 specification. In other words, it is an error to call this function more 

1054 than once in a class definition. 

1055 

1056 Note that the given interfaces have nothing to do with the interfaces 

1057 implemented by instances of the class. 

1058 

1059 This function is provided for convenience. It provides a more convenient 

1060 way to call `directlyProvides` for a class. For example:: 

1061 

1062 classProvides(I1) 

1063 

1064 is equivalent to calling:: 

1065 

1066 directlyProvides(theclass, I1) 

1067 

1068 after the class has been created. 

1069 """ 

1070 # This entire approach is invalid under Py3K. Don't even try to fix 

1071 # the coverage for this block there. :( 

1072 

1073 if PYTHON3: 

1074 raise TypeError(_ADVICE_ERROR % 'provider') 

1075 

1076 frame = sys._getframe(1) # pylint:disable=protected-access 

1077 locals = frame.f_locals # pylint:disable=redefined-builtin 

1078 

1079 # Try to make sure we were called from a class def 

1080 if (locals is frame.f_globals) or ('__module__' not in locals): 

1081 raise TypeError("classProvides can be used only from a " 

1082 "class definition.") 

1083 

1084 if '__provides__' in locals: 

1085 raise TypeError( 

1086 "classProvides can only be used once in a class definition.") 

1087 

1088 locals["__provides__"] = _normalizeargs(interfaces) 

1089 

1090 addClassAdvisor(_classProvides_advice, depth=2) 

1091 

1092def _classProvides_advice(cls): 

1093 # This entire approach is invalid under Py3K. Don't even try to fix 

1094 # the coverage for this block there. :( 

1095 interfaces = cls.__dict__['__provides__'] 

1096 del cls.__provides__ 

1097 directlyProvides(cls, *interfaces) 

1098 return cls 

1099 

1100 

1101class provider(object): 

1102 """Class decorator version of classProvides""" 

1103 

1104 def __init__(self, *interfaces): 

1105 self.interfaces = interfaces 

1106 

1107 def __call__(self, ob): 

1108 directlyProvides(ob, *self.interfaces) 

1109 return ob 

1110 

1111 

1112def moduleProvides(*interfaces): 

1113 """Declare interfaces provided by a module 

1114 

1115 This function is used in a module definition. 

1116 

1117 The arguments are one or more interfaces or interface specifications 

1118 (`~zope.interface.interfaces.IDeclaration` objects). 

1119 

1120 The given interfaces (including the interfaces in the specifications) are 

1121 used to create the module's direct-object interface specification. An 

1122 error will be raised if the module already has an interface specification. 

1123 In other words, it is an error to call this function more than once in a 

1124 module definition. 

1125 

1126 This function is provided for convenience. It provides a more convenient 

1127 way to call directlyProvides. For example:: 

1128 

1129 moduleProvides(I1) 

1130 

1131 is equivalent to:: 

1132 

1133 directlyProvides(sys.modules[__name__], I1) 

1134 """ 

1135 frame = sys._getframe(1) # pylint:disable=protected-access 

1136 locals = frame.f_locals # pylint:disable=redefined-builtin 

1137 

1138 # Try to make sure we were called from a module body 

1139 if (locals is not frame.f_globals) or ('__name__' not in locals): 

1140 raise TypeError( 

1141 "moduleProvides can only be used from a module definition.") 

1142 

1143 if '__provides__' in locals: 

1144 raise TypeError( 

1145 "moduleProvides can only be used once in a module definition.") 

1146 

1147 # Note: This is cached based on the key ``(ModuleType, *interfaces)``; 

1148 # One consequence is that any module that provides the same interfaces 

1149 # gets the same ``__repr__``, meaning that you can't tell what module 

1150 # such a declaration came from. Adding the module name to ``_v_module_names`` 

1151 # attempts to correct for this; it works in some common situations, but fails 

1152 # (1) after pickling (the data is lost) and (2) if declarations are 

1153 # actually shared and (3) if the alternate spelling of ``directlyProvides()`` 

1154 # is used. Problem (3) is fixed by cooperating with ``directlyProvides`` 

1155 # to maintain this information, and problem (2) is worked around by 

1156 # printing all the names, but (1) is unsolvable without introducing 

1157 # new classes or changing the stored data...but it doesn't actually matter, 

1158 # because ``ModuleType`` can't be pickled! 

1159 p = locals["__provides__"] = Provides(ModuleType, 

1160 *_normalizeargs(interfaces)) 

1161 p._v_module_names += (locals['__name__'],) 

1162 

1163 

1164############################################################################## 

1165# 

1166# Declaration querying support 

1167 

1168# XXX: is this a fossil? Nobody calls it, no unit tests exercise it, no 

1169# doctests import it, and the package __init__ doesn't import it. 

1170# (Answer: Versions of zope.container prior to 4.4.0 called this, 

1171# and zope.proxy.decorator up through at least 4.3.5 called this.) 

1172def ObjectSpecification(direct, cls): 

1173 """Provide object specifications 

1174 

1175 These combine information for the object and for it's classes. 

1176 """ 

1177 return Provides(cls, direct) # pragma: no cover fossil 

1178 

1179@_use_c_impl 

1180def getObjectSpecification(ob): 

1181 try: 

1182 provides = ob.__provides__ 

1183 except AttributeError: 

1184 provides = None 

1185 

1186 if provides is not None: 

1187 if isinstance(provides, SpecificationBase): 

1188 return provides 

1189 

1190 try: 

1191 cls = ob.__class__ 

1192 except AttributeError: 

1193 # We can't get the class, so just consider provides 

1194 return _empty 

1195 return implementedBy(cls) 

1196 

1197 

1198@_use_c_impl 

1199def providedBy(ob): 

1200 """ 

1201 Return the interfaces provided by *ob*. 

1202 

1203 If *ob* is a :class:`super` object, then only interfaces implemented 

1204 by the remainder of the classes in the method resolution order are 

1205 considered. Interfaces directly provided by the object underlying *ob* 

1206 are not. 

1207 """ 

1208 # Here we have either a special object, an old-style declaration 

1209 # or a descriptor 

1210 

1211 # Try to get __providedBy__ 

1212 try: 

1213 if isinstance(ob, super): # Some objects raise errors on isinstance() 

1214 return implementedBy(ob) 

1215 

1216 r = ob.__providedBy__ 

1217 except AttributeError: 

1218 # Not set yet. Fall back to lower-level thing that computes it 

1219 return getObjectSpecification(ob) 

1220 

1221 try: 

1222 # We might have gotten a descriptor from an instance of a 

1223 # class (like an ExtensionClass) that doesn't support 

1224 # descriptors. We'll make sure we got one by trying to get 

1225 # the only attribute, which all specs have. 

1226 r.extends 

1227 except AttributeError: 

1228 

1229 # The object's class doesn't understand descriptors. 

1230 # Sigh. We need to get an object descriptor, but we have to be 

1231 # careful. We want to use the instance's __provides__, if 

1232 # there is one, but only if it didn't come from the class. 

1233 

1234 try: 

1235 r = ob.__provides__ 

1236 except AttributeError: 

1237 # No __provides__, so just fall back to implementedBy 

1238 return implementedBy(ob.__class__) 

1239 

1240 # We need to make sure we got the __provides__ from the 

1241 # instance. We'll do this by making sure we don't get the same 

1242 # thing from the class: 

1243 

1244 try: 

1245 cp = ob.__class__.__provides__ 

1246 except AttributeError: 

1247 # The ob doesn't have a class or the class has no 

1248 # provides, assume we're done: 

1249 return r 

1250 

1251 if r is cp: 

1252 # Oops, we got the provides from the class. This means 

1253 # the object doesn't have it's own. We should use implementedBy 

1254 return implementedBy(ob.__class__) 

1255 

1256 return r 

1257 

1258 

1259@_use_c_impl 

1260class ObjectSpecificationDescriptor(object): 

1261 """Implement the ``__providedBy__`` attribute 

1262 

1263 The ``__providedBy__`` attribute computes the interfaces provided by 

1264 an object. If an object has an ``__provides__`` attribute, that is returned. 

1265 Otherwise, `implementedBy` the *cls* is returned. 

1266 

1267 .. versionchanged:: 5.4.0 

1268 Both the default (C) implementation and the Python implementation 

1269 now let exceptions raised by accessing ``__provides__`` propagate. 

1270 Previously, the C version ignored all exceptions. 

1271 .. versionchanged:: 5.4.0 

1272 The Python implementation now matches the C implementation and lets 

1273 a ``__provides__`` of ``None`` override what the class is declared to 

1274 implement. 

1275 """ 

1276 

1277 def __get__(self, inst, cls): 

1278 """Get an object specification for an object 

1279 """ 

1280 if inst is None: 

1281 return getObjectSpecification(cls) 

1282 

1283 try: 

1284 return inst.__provides__ 

1285 except AttributeError: 

1286 return implementedBy(cls) 

1287 

1288 

1289############################################################################## 

1290 

1291def _normalizeargs(sequence, output=None): 

1292 """Normalize declaration arguments 

1293 

1294 Normalization arguments might contain Declarions, tuples, or single 

1295 interfaces. 

1296 

1297 Anything but individial interfaces or implements specs will be expanded. 

1298 """ 

1299 if output is None: 

1300 output = [] 

1301 

1302 cls = sequence.__class__ 

1303 if InterfaceClass in cls.__mro__ or Implements in cls.__mro__: 

1304 output.append(sequence) 

1305 else: 

1306 for v in sequence: 

1307 _normalizeargs(v, output) 

1308 

1309 return output 

1310 

1311_empty = _ImmutableDeclaration() 

1312 

1313objectSpecificationDescriptor = ObjectSpecificationDescriptor()