aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/zope.interface-3.6.4-py2.7-linux-x86_64.egg/zope/interface/declarations.py
blob: 3ee27c41a7f480e40d8c6c9795214fda6bfca09c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
##############################################################################
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
##############################################################################
"""Implementation of interface declarations

There are three flavors of declarations:

  - Declarations are used to simply name declared interfaces.

  - ImplementsDeclarations are used to express the interfaces that a
    class implements (that instances of the class provides).

    Implements specifications support inheriting interfaces.

  - ProvidesDeclarations are used to express interfaces directly
    provided by objects.

"""
__docformat__ = 'restructuredtext'

import sys
import weakref
from zope.interface.interface import InterfaceClass, Specification
from zope.interface.interface import SpecificationBase
from types import ModuleType, MethodType, FunctionType
from zope.interface.advice import addClassAdvisor

# Registry of class-implementation specifications
BuiltinImplementationSpecifications = {}

class Declaration(Specification):
    """Interface declarations"""

    def __init__(self, *interfaces):
        Specification.__init__(self, _normalizeargs(interfaces))

    def changed(self, originally_changed):
        Specification.changed(self, originally_changed)
        try:
            del self._v_attrs
        except AttributeError:
            pass

    def __contains__(self, interface):
        """Test whether an interface is in the specification

        for example:

          >>> from zope.interface import Interface
          >>> class I1(Interface): pass
          ...
          >>> class I2(I1): pass
          ...
          >>> class I3(Interface): pass
          ...
          >>> class I4(I3): pass
          ...
          >>> spec = Declaration(I2, I3)
          >>> spec = Declaration(I4, spec)
          >>> int(I1 in spec)
          0
          >>> int(I2 in spec)
          1
          >>> int(I3 in spec)
          1
          >>> int(I4 in spec)
          1
        """
        return self.extends(interface) and interface in self.interfaces()

    def __iter__(self):
        """Return an iterator for the interfaces in the specification

        for example:

          >>> from zope.interface import Interface
          >>> class I1(Interface): pass
          ...
          >>> class I2(I1): pass
          ...
          >>> class I3(Interface): pass
          ...
          >>> class I4(I3): pass
          ...
          >>> spec = Declaration(I2, I3)
          >>> spec = Declaration(I4, spec)
          >>> i = iter(spec)
          >>> [x.getName() for x in i]
          ['I4', 'I2', 'I3']
          >>> list(i)
          []
        """
        return self.interfaces()

    def flattened(self):
        """Return an iterator of all included and extended interfaces

        for example:

          >>> from zope.interface import Interface
          >>> class I1(Interface): pass
          ...
          >>> class I2(I1): pass
          ...
          >>> class I3(Interface): pass
          ...
          >>> class I4(I3): pass
          ...
          >>> spec = Declaration(I2, I3)
          >>> spec = Declaration(I4, spec)
          >>> i = spec.flattened()
          >>> [x.getName() for x in i]
          ['I4', 'I2', 'I1', 'I3', 'Interface']
          >>> list(i)
          []

        """
        return iter(self.__iro__)

    def __sub__(self, other):
        """Remove interfaces from a specification

        Examples:

          >>> from zope.interface import Interface
          >>> class I1(Interface): pass
          ...
          >>> class I2(I1): pass
          ...
          >>> class I3(Interface): pass
          ...
          >>> class I4(I3): pass
          ...
          >>> spec = Declaration()
          >>> [iface.getName() for iface in spec]
          []
          >>> spec -= I1
          >>> [iface.getName() for iface in spec]
          []
          >>> spec -= Declaration(I1, I2)
          >>> [iface.getName() for iface in spec]
          []
          >>> spec = Declaration(I2, I4)
          >>> [iface.getName() for iface in spec]
          ['I2', 'I4']
          >>> [iface.getName() for iface in spec - I4]
          ['I2']
          >>> [iface.getName() for iface in spec - I1]
          ['I4']
          >>> [iface.getName() for iface
          ...  in spec - Declaration(I3, I4)]
          ['I2']

        """

        return Declaration(
            *[i for i in self.interfaces()
                if not [j for j in other.interfaces()
                        if i.extends(j, 0)]
                ]
                )

    def __add__(self, other):
        """Add two specifications or a specification and an interface

        Examples:

          >>> from zope.interface import Interface
          >>> class I1(Interface): pass
          ...
          >>> class I2(I1): pass
          ...
          >>> class I3(Interface): pass
          ...
          >>> class I4(I3): pass
          ...
          >>> spec = Declaration()
          >>> [iface.getName() for iface in spec]
          []
          >>> [iface.getName() for iface in spec+I1]
          ['I1']
          >>> [iface.getName() for iface in I1+spec]
          ['I1']
          >>> spec2 = spec
          >>> spec += I1
          >>> [iface.getName() for iface in spec]
          ['I1']
          >>> [iface.getName() for iface in spec2]
          []
          >>> spec2 += Declaration(I3, I4)
          >>> [iface.getName() for iface in spec2]
          ['I3', 'I4']
          >>> [iface.getName() for iface in spec+spec2]
          ['I1', 'I3', 'I4']
          >>> [iface.getName() for iface in spec2+spec]
          ['I3', 'I4', 'I1']

        """

        seen = {}
        result = []
        for i in self.interfaces():
            if i not in seen:
                seen[i] = 1
                result.append(i)
        for i in other.interfaces():
            if i not in seen:
                seen[i] = 1
                result.append(i)

        return Declaration(*result)

    __radd__ = __add__


##############################################################################
#
# Implementation specifications
#
# These specify interfaces implemented by instances of classes

class Implements(Declaration):

    # class whose specification should be used as additional base
    inherit = None

    # interfaces actually declared for a class
    declared = ()

    __name__ = '?'

    def __repr__(self):
        return '<implementedBy %s>' % (self.__name__)

    def __reduce__(self):
        return implementedBy, (self.inherit, )

def implementedByFallback(cls):
    """Return the interfaces implemented for a class' instances

      The value returned is an IDeclaration.

      for example:

        >>> from zope.interface import Interface
        >>> class I1(Interface): pass
        ...
        >>> class I2(I1): pass
        ...
        >>> class I3(Interface): pass
        ...
        >>> class I4(I3): pass
        ...
        >>> class C1(object):
        ...   implements(I2)
        >>> class C2(C1):
        ...   implements(I3)
        >>> [i.getName() for i in implementedBy(C2)]
        ['I3', 'I2']

      Really, any object should be able to receive a successful answer, even
      an instance:

        >>> class Callable(object):
        ...     def __call__(self):
        ...         return self

        >>> implementedBy(Callable())
        <implementedBy zope.interface.declarations.?>

      Note that the name of the spec ends with a '?', because the `Callable`
      instance does not have a `__name__` attribute.
      """
    # This also manages storage of implementation specifications

    try:
        spec = cls.__dict__.get('__implemented__')
    except AttributeError:

        # we can't get the class dict. This is probably due to a
        # security proxy.  If this is the case, then probably no
        # descriptor was installed for the class.

        # We don't want to depend directly on zope.security in
        # zope.interface, but we'll try to make reasonable
        # accommodations in an indirect way.

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

        spec = getattr(cls, '__implemented__', None)
        if spec is None:
            # There's no spec stred in the class. Maybe its a builtin:
            spec = BuiltinImplementationSpecifications.get(cls)
            if spec is not None:
                return spec
            return _empty

        if spec.__class__ == Implements:
            # we defaulted to _empty or there was a spec. Good enough.
            # Return it.
            return spec

        # TODO: need old style __implements__ compatibility?
        # Hm, there's an __implemented__, but it's not a spec. Must be
        # an old-style declaration. Just compute a spec for it
        return Declaration(*_normalizeargs((spec, )))

    if isinstance(spec, Implements):
        return spec

    if spec is None:
        spec = BuiltinImplementationSpecifications.get(cls)
        if spec is not None:
            return spec

    # TODO: need old style __implements__ compatibility?
    if spec is not None:
        # old-style __implemented__ = foo declaration
        spec = (spec, ) # tuplefy, as it might be just an int
        spec = Implements(*_normalizeargs(spec))
        spec.inherit = None    # old-style implies no inherit
        del cls.__implemented__ # get rid of the old-style declaration
    else:
        try:
            bases = cls.__bases__
        except AttributeError:
            if not callable(cls):
                raise TypeError("ImplementedBy called for non-factory", cls)
            bases = ()

        spec = Implements(*[implementedBy(c) for c in bases])
        spec.inherit = cls

    spec.__name__ = (getattr(cls, '__module__', '?') or '?') + \
                    '.' + (getattr(cls, '__name__', '?') or '?')

    try:
        cls.__implemented__ = spec
        if not hasattr(cls, '__providedBy__'):
            cls.__providedBy__ = objectSpecificationDescriptor

        if (isinstance(cls, DescriptorAwareMetaClasses)
            and
            '__provides__' not in cls.__dict__):
            # Make sure we get a __provides__ descriptor
            cls.__provides__ = ClassProvides(
                cls,
                getattr(cls, '__class__', type(cls)),
                )

    except TypeError:
        if not isinstance(cls, type):
            raise TypeError("ImplementedBy called for non-type", cls)
        BuiltinImplementationSpecifications[cls] = spec

    return spec

implementedBy = implementedByFallback

def classImplementsOnly(cls, *interfaces):
    """Declare the only interfaces implemented by instances of a class

      The arguments after the class are one or more interfaces or interface
      specifications (``IDeclaration`` objects).

      The interfaces given (including the interfaces in the specifications)
      replace any previous declarations.

      Consider the following example:

        >>> from zope.interface import Interface
        >>> class I1(Interface): pass
        ...
        >>> class I2(Interface): pass
        ...
        >>> class I3(Interface): pass
        ...
        >>> class I4(Interface): pass
        ...
        >>> class A(object):
        ...   implements(I3)
        >>> class B(object):
        ...   implements(I4)
        >>> class C(A, B):
        ...   pass
        >>> classImplementsOnly(C, I1, I2)
        >>> [i.getName() for i in implementedBy(C)]
        ['I1', 'I2']

      Instances of ``C`` provide only ``I1``, ``I2``, and regardless of
      whatever interfaces instances of ``A`` and ``B`` implement.
      """
    spec = implementedBy(cls)
    spec.declared = ()
    spec.inherit = None
    classImplements(cls, *interfaces)

def classImplements(cls, *interfaces):
    """Declare additional interfaces implemented for instances of a class

      The arguments after the class are one or more interfaces or
      interface specifications (``IDeclaration`` objects).

      The interfaces given (including the interfaces in the specifications)
      are added to any interfaces previously declared.

      Consider the following example:

        >>> from zope.interface import Interface
        >>> class I1(Interface): pass
        ...
        >>> class I2(Interface): pass
        ...
        >>> class I3(Interface): pass
        ...
        >>> class I4(Interface): pass
        ...
        >>> class I5(Interface): pass
        ...
        >>> class A(object):
        ...   implements(I3)
        >>> class B(object):
        ...   implements(I4)
        >>> class C(A, B):
        ...   pass
        >>> classImplements(C, I1, I2)
        >>> [i.getName() for i in implementedBy(C)]
        ['I1', 'I2', 'I3', 'I4']
        >>> classImplements(C, I5)
        >>> [i.getName() for i in implementedBy(C)]
        ['I1', 'I2', 'I5', 'I3', 'I4']

      Instances of ``C`` provide ``I1``, ``I2``, ``I5``, and whatever
      interfaces instances of ``A`` and ``B`` provide.
      """

    spec = implementedBy(cls)
    spec.declared += tuple(_normalizeargs(interfaces))

    # compute the bases
    bases = []
    seen = {}
    for b in spec.declared:
        if b not in seen:
            seen[b] = 1
            bases.append(b)

    if spec.inherit is not None:

        for c in spec.inherit.__bases__:
            b = implementedBy(c)
            if b not in seen:
                seen[b] = 1
                bases.append(b)            

    spec.__bases__ = tuple(bases)

def _implements_advice(cls):
    interfaces, classImplements = cls.__dict__['__implements_advice_data__']
    del cls.__implements_advice_data__
    classImplements(cls, *interfaces)
    return cls


class implementer:

    def __init__(self, *interfaces):
        self.interfaces = interfaces

    def __call__(self, ob):
        if isinstance(ob, DescriptorAwareMetaClasses):
            classImplements(ob, *self.interfaces)
            return ob            
        
        spec = Implements(*self.interfaces)
        try:
            ob.__implemented__ = spec
        except AttributeError:
            raise TypeError("Can't declare implements", ob)
        return ob

class implementer_only:

    def __init__(self, *interfaces):
        self.interfaces = interfaces

    def __call__(self, ob):
        if isinstance(ob, (FunctionType, MethodType)):
            # XXX Does this decorator make sense for anything but classes?
            # I don't think so. There can be no inheritance of interfaces
            # on a method pr function....
            raise ValueError('The implementor_only decorator is not '
                             'supported for methods or functions.')
        else:
            # Assume it's a class:
            classImplementsOnly(ob, *self.interfaces)
            return ob            
        
def _implements(name, interfaces, classImplements):
    frame = sys._getframe(2)
    locals = frame.f_locals

    # Try to make sure we were called from a class def. In 2.2.0 we can't
    # check for __module__ since it doesn't seem to be added to the locals
    # until later on.
    if (locals is frame.f_globals) or (
        ('__module__' not in locals) and sys.version_info[:3] > (2, 2, 0)):
        raise TypeError(name+" can be used only from a class definition.")

    if '__implements_advice_data__' in locals:
        raise TypeError(name+" can be used only once in a class definition.")

    locals['__implements_advice_data__'] = interfaces, classImplements
    addClassAdvisor(_implements_advice, depth=3)

def implements(*interfaces):
    """Declare interfaces implemented by instances of a class

      This function is called in a class definition.

      The arguments are one or more interfaces or interface
      specifications (IDeclaration objects).

      The interfaces given (including the interfaces in the
      specifications) are added to any interfaces previously
      declared.

      Previous declarations include declarations for base classes
      unless implementsOnly was used.

      This function is provided for convenience. It provides a more
      convenient way to call classImplements. For example::

        implements(I1)

      is equivalent to calling::

        classImplements(C, I1)

      after the class has been created.

      Consider the following example::


        >>> from zope.interface import Interface
        >>> class IA1(Interface): pass
        ...
        >>> class IA2(Interface): pass
        ...
        >>> class IB(Interface): pass
        ...
        >>> class IC(Interface): pass
        ...
        >>> class A(object):
        ...     implements(IA1, IA2)
        >>> class B(object):
        ...     implements(IB)

        >>> class C(A, B):
        ...    implements(IC)

        >>> ob = C()
        >>> int(IA1 in providedBy(ob))
        1
        >>> int(IA2 in providedBy(ob))
        1
        >>> int(IB in providedBy(ob))
        1
        >>> int(IC in providedBy(ob))
        1

      Instances of ``C`` implement ``I1``, ``I2``, and whatever interfaces
      instances of ``A`` and ``B`` implement.

      """
    _implements("implements", interfaces, classImplements)

def implementsOnly(*interfaces):
    """Declare the only interfaces implemented by instances of a class

      This function is called in a class definition.

      The arguments are one or more interfaces or interface
      specifications (IDeclaration objects).

      Previous declarations including declarations for base classes
      are overridden.

      This function is provided for convenience. It provides a more
      convenient way to call classImplementsOnly. For example::

        implementsOnly(I1)

      is equivalent to calling::

        classImplementsOnly(I1)

      after the class has been created.

      Consider the following example::

        >>> from zope.interface import Interface
        >>> class IA1(Interface): pass
        ...
        >>> class IA2(Interface): pass
        ...
        >>> class IB(Interface): pass
        ...
        >>> class IC(Interface): pass
        ...
        >>> class A(object):
        ...     implements(IA1, IA2)
        >>> class B(object):
        ...     implements(IB)

        >>> class C(A, B):
        ...    implementsOnly(IC)

        >>> ob = C()
        >>> int(IA1 in providedBy(ob))
        0
        >>> int(IA2 in providedBy(ob))
        0
        >>> int(IB in providedBy(ob))
        0
        >>> int(IC in providedBy(ob))
        1


      Instances of ``C`` implement ``IC``, regardless of what
      instances of ``A`` and ``B`` implement.

      """
    _implements("implementsOnly", interfaces, classImplementsOnly)

##############################################################################
#
# Instance declarations

class Provides(Declaration):  # Really named ProvidesClass
    """Implement __provides__, the instance-specific specification

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

    def __init__(self, cls, *interfaces):
        self.__args = (cls, ) + interfaces
        self._cls = cls
        Declaration.__init__(self, *(interfaces + (implementedBy(cls), )))

    def __reduce__(self):
        return Provides, self.__args

    __module__ = 'zope.interface'

    def __get__(self, inst, cls):
        """Make sure that a class __provides__ doesn't leak to an instance

        For example:

          >>> from zope.interface import Interface
          >>> class IFooFactory(Interface): pass
          ...

          >>> class C(object):
          ...   pass

          >>> C.__provides__ = ProvidesClass(C, IFooFactory)
          >>> [i.getName() for i in C.__provides__]
          ['IFooFactory']
          >>> getattr(C(), '__provides__', 0)
          0

        """
        if inst is None and cls is self._cls:
            # We were accessed through a class, so we are the class'
            # provides spec. Just return this object, but only if we are
            # being called on the same class that we were defined for:
            return self

        raise AttributeError('__provides__')

ProvidesClass = Provides

# Registry of instance declarations
# This is a memory optimization to allow objects to share specifications.
InstanceDeclarations = weakref.WeakValueDictionary()

def Provides(*interfaces):
    """Cache instance declarations

      Instance declarations are shared among instances that have the same
      declaration. The declarations are cached in a weak value dictionary.

      (Note that, in the examples below, we are going to make assertions about
       the size of the weakvalue dictionary.  For the assertions to be
       meaningful, we need to force garbage collection to make sure garbage
       objects are, indeed, removed from the system. Depending on how Python
       is run, we may need to make multiple calls to be sure.  We provide a
       collect function to help with this:

       >>> import gc
       >>> def collect():
       ...     for i in range(4):
       ...         gc.collect()

      )

      >>> collect()
      >>> before = len(InstanceDeclarations)

      >>> class C(object):
      ...    pass

      >>> from zope.interface import Interface
      >>> class I(Interface):
      ...    pass

      >>> c1 = C()
      >>> c2 = C()

      >>> len(InstanceDeclarations) == before
      1

      >>> directlyProvides(c1, I)
      >>> len(InstanceDeclarations) == before + 1
      1

      >>> directlyProvides(c2, I)
      >>> len(InstanceDeclarations) == before + 1
      1

      >>> del c1
      >>> collect()
      >>> len(InstanceDeclarations) == before + 1
      1

      >>> del c2
      >>> collect()
      >>> len(InstanceDeclarations) == before
      1
      """

    spec = InstanceDeclarations.get(interfaces)
    if spec is None:
        spec = ProvidesClass(*interfaces)
        InstanceDeclarations[interfaces] = spec

    return spec
Provides.__safe_for_unpickling__ = True

try:
    from types import ClassType
    DescriptorAwareMetaClasses = ClassType, type
except ImportError: # Python 3
    DescriptorAwareMetaClasses = (type,)
    
def directlyProvides(object, *interfaces):
    """Declare interfaces declared directly for an object

      The arguments after the object are one or more interfaces or interface
      specifications (``IDeclaration`` objects).

      The interfaces given (including the interfaces in the specifications)
      replace interfaces previously declared for the object.

      Consider the following example:

        >>> from zope.interface import Interface
        >>> class I1(Interface): pass
        ...
        >>> class I2(Interface): pass
        ...
        >>> class IA1(Interface): pass
        ...
        >>> class IA2(Interface): pass
        ...
        >>> class IB(Interface): pass
        ...
        >>> class IC(Interface): pass
        ...
        >>> class A(object):
        ...     implements(IA1, IA2)
        >>> class B(object):
        ...     implements(IB)

        >>> class C(A, B):
        ...    implements(IC)

        >>> ob = C()
        >>> directlyProvides(ob, I1, I2)
        >>> int(I1 in providedBy(ob))
        1
        >>> int(I2 in providedBy(ob))
        1
        >>> int(IA1 in providedBy(ob))
        1
        >>> int(IA2 in providedBy(ob))
        1
        >>> int(IB in providedBy(ob))
        1
        >>> int(IC in providedBy(ob))
        1

      The object, ``ob`` provides ``I1``, ``I2``, and whatever interfaces
      instances have been declared for instances of ``C``.

      To remove directly provided interfaces, use ``directlyProvidedBy`` and
      subtract the unwanted interfaces. For example:

        >>> directlyProvides(ob, directlyProvidedBy(ob)-I2)
        >>> int(I1 in providedBy(ob))
        1
        >>> int(I2 in providedBy(ob))
        0

      removes I2 from the interfaces directly provided by ``ob``. The object,
      ``ob`` no longer directly provides ``I2``, although it might still
      provide ``I2`` if it's class implements ``I2``.

      To add directly provided interfaces, use ``directlyProvidedBy`` and
      include additional interfaces.  For example:

        >>> int(I2 in providedBy(ob))
        0
        >>> directlyProvides(ob, directlyProvidedBy(ob), I2)

      adds ``I2`` to the interfaces directly provided by ob::

        >>> int(I2 in providedBy(ob))
        1

      """

    # We need to avoid setting this attribute on meta classes that
    # don't support descriptors.
    # We can do away with this check when we get rid of the old EC
    cls = getattr(object, '__class__', None)
    if cls is not None and getattr(cls,  '__class__', None) is cls:
        # It's a meta class (well, at least it it could be an extension class)
        if not isinstance(object, DescriptorAwareMetaClasses):
            raise TypeError("Attempt to make an interface declaration on a "
                            "non-descriptor-aware class")

    interfaces = _normalizeargs(interfaces)
    if cls is None:
        cls = type(object)

    issub = False
    for damc in DescriptorAwareMetaClasses:
        if issubclass(cls, damc):
            issub = True
            break
    if issub:
        # we have a class or type.  We'll use a special descriptor
        # that provides some extra caching
        object.__provides__ = ClassProvides(object, cls, *interfaces)
    else:
        object.__provides__ = Provides(cls, *interfaces)


def alsoProvides(object, *interfaces):
    """Declare interfaces declared directly for an object

    The arguments after the object are one or more interfaces or interface
    specifications (``IDeclaration`` objects).

    The interfaces given (including the interfaces in the specifications) are
    added to the interfaces previously declared for the object.

    Consider the following example:

      >>> from zope.interface import Interface
      >>> class I1(Interface): pass
      ...
      >>> class I2(Interface): pass
      ...
      >>> class IA1(Interface): pass
      ...
      >>> class IA2(Interface): pass
      ...
      >>> class IB(Interface): pass
      ...
      >>> class IC(Interface): pass
      ...
      >>> class A(object):
      ...     implements(IA1, IA2)
      >>> class B(object):
      ...     implements(IB)

      >>> class C(A, B):
      ...    implements(IC)

      >>> ob = C()
      >>> directlyProvides(ob, I1)
      >>> int(I1 in providedBy(ob))
      1
      >>> int(I2 in providedBy(ob))
      0
      >>> int(IA1 in providedBy(ob))
      1
      >>> int(IA2 in providedBy(ob))
      1
      >>> int(IB in providedBy(ob))
      1
      >>> int(IC in providedBy(ob))
      1

      >>> alsoProvides(ob, I2)
      >>> int(I1 in providedBy(ob))
      1
      >>> int(I2 in providedBy(ob))
      1
      >>> int(IA1 in providedBy(ob))
      1
      >>> int(IA2 in providedBy(ob))
      1
      >>> int(IB in providedBy(ob))
      1
      >>> int(IC in providedBy(ob))
      1

    The object, ``ob`` provides ``I1``, ``I2``, and whatever interfaces
    instances have been declared for instances of ``C``. Notice that the
    alsoProvides just extends the provided interfaces.
    """
    directlyProvides(object, directlyProvidedBy(object), *interfaces)

def noLongerProvides(object, interface):
    """
    This removes a directly provided interface from an object.
    Consider the following two interfaces:

      >>> from zope.interface import Interface
      >>> class I1(Interface): pass
      ...
      >>> class I2(Interface): pass
      ...

    ``I1`` is provided through the class, ``I2`` is directly provided
    by the object:
    
      >>> class C(object):
      ...    implements(I1)
      >>> c = C()
      >>> alsoProvides(c, I2)
      >>> I2.providedBy(c)
      True

    Remove I2 from c again:
      
      >>> noLongerProvides(c, I2)
      >>> I2.providedBy(c)
      False

    Removing an interface that is provided through the class is not possible:

      >>> noLongerProvides(c, I1)
      Traceback (most recent call last):
      ...
      ValueError: Can only remove directly provided interfaces.

    """
    directlyProvides(object, directlyProvidedBy(object)-interface)
    if interface.providedBy(object):
        raise ValueError("Can only remove directly provided interfaces.")

class ClassProvidesBasePy(object):

    def __get__(self, inst, cls):
        if cls is self._cls:
            # We only work if called on the class we were defined for

            if inst is None:
                # We were accessed through a class, so we are the class'
                # provides spec. Just return this object as is:
                return self

            return self._implements

        raise AttributeError('__provides__')

ClassProvidesBase = ClassProvidesBasePy

# Try to get C base:
try:
    import _zope_interface_coptimizations
except ImportError:
    pass
else:
    from _zope_interface_coptimizations import ClassProvidesBase


class ClassProvides(Declaration, ClassProvidesBase):
    """Special descriptor for class __provides__

    The descriptor caches the implementedBy info, so that
    we can get declarations for objects without instance-specific
    interfaces a bit quicker.

    For example:

      >>> from zope.interface import Interface
      >>> class IFooFactory(Interface):
      ...     pass
      >>> class IFoo(Interface):
      ...     pass
      >>> class C(object):
      ...     implements(IFoo)
      ...     classProvides(IFooFactory)
      >>> [i.getName() for i in C.__provides__]
      ['IFooFactory']

      >>> [i.getName() for i in C().__provides__]
      ['IFoo']
    """

    def __init__(self, cls, metacls, *interfaces):
        self._cls = cls
        self._implements = implementedBy(cls)
        self.__args = (cls, metacls, ) + interfaces
        Declaration.__init__(self, *(interfaces + (implementedBy(metacls), )))

    def __reduce__(self):
        return self.__class__, self.__args

    # Copy base-class method for speed
    __get__ = ClassProvidesBase.__get__

def directlyProvidedBy(object):
    """Return the interfaces directly provided by the given object

    The value returned is an ``IDeclaration``.
    """
    provides = getattr(object, "__provides__", None)
    if (provides is None # no spec
        or
        # We might have gotten the implements spec, as an
        # optimization. If so, it's like having only one base, that we
        # lop off to exclude class-supplied declarations:
        isinstance(provides, Implements)
        ):
        return _empty

    # Strip off the class part of the spec:
    return Declaration(provides.__bases__[:-1])

def classProvides(*interfaces):
    """Declare interfaces provided directly by a class

      This function is called in a class definition.

      The arguments are one or more interfaces or interface specifications
      (``IDeclaration`` objects).

      The given interfaces (including the interfaces in the specifications)
      are used to create the class's direct-object interface specification.
      An error will be raised if the module class has an direct interface
      specification. In other words, it is an error to call this function more
      than once in a class definition.

      Note that the given interfaces have nothing to do with the interfaces
      implemented by instances of the class.

      This function is provided for convenience. It provides a more convenient
      way to call directlyProvides for a class. For example::

        classProvides(I1)

      is equivalent to calling::

        directlyProvides(theclass, I1)

      after the class has been created.

      For example:

        >>> from zope.interface import Interface
        >>> class IFoo(Interface): pass
        ...
        >>> class IFooFactory(Interface): pass
        ...
        >>> class C(object):
        ...   implements(IFoo)
        ...   classProvides(IFooFactory)
        >>> [i.getName() for i in C.__providedBy__]
        ['IFooFactory']
        >>> [i.getName() for i in C().__providedBy__]
        ['IFoo']

      if equivalent to:

        >>> from zope.interface import Interface
        >>> class IFoo(Interface): pass
        ...
        >>> class IFooFactory(Interface): pass
        ...
        >>> class C(object):
        ...   implements(IFoo)
        >>> directlyProvides(C, IFooFactory)
        >>> [i.getName() for i in C.__providedBy__]
        ['IFooFactory']
        >>> [i.getName() for i in C().__providedBy__]
        ['IFoo']

      """
    frame = sys._getframe(1)
    locals = frame.f_locals

    # Try to make sure we were called from a class def
    if (locals is frame.f_globals) or ('__module__' not in locals):
        raise TypeError("classProvides can be used only from a class definition.")

    if '__provides__' in locals:
        raise TypeError(
            "classProvides can only be used once in a class definition.")

    locals["__provides__"] = _normalizeargs(interfaces)

    addClassAdvisor(_classProvides_advice, depth=2)

def _classProvides_advice(cls):
    interfaces = cls.__dict__['__provides__']
    del cls.__provides__
    directlyProvides(cls, *interfaces)
    return cls

class provider:
    """Class decorator version of classProvides"""

    def __init__(self, *interfaces):
        self.interfaces = interfaces

    def __call__(self, ob):
        directlyProvides(ob, *self.interfaces)
        return ob            

def moduleProvides(*interfaces):
    """Declare interfaces provided by a module

    This function is used in a module definition.

    The arguments are one or more interfaces or interface specifications
    (``IDeclaration`` objects).

    The given interfaces (including the interfaces in the specifications) are
    used to create the module's direct-object interface specification.  An
    error will be raised if the module already has an interface specification.
    In other words, it is an error to call this function more than once in a
    module definition.

    This function is provided for convenience. It provides a more convenient
    way to call directlyProvides. For example::

      moduleImplements(I1)

    is equivalent to::

      directlyProvides(sys.modules[__name__], I1)
    """
    frame = sys._getframe(1)
    locals = frame.f_locals

    # Try to make sure we were called from a class def
    if (locals is not frame.f_globals) or ('__name__' not in locals):
        raise TypeError(
            "moduleProvides can only be used from a module definition.")

    if '__provides__' in locals:
        raise TypeError(
            "moduleProvides can only be used once in a module definition.")

    locals["__provides__"] = Provides(ModuleType,
                                      *_normalizeargs(interfaces))

##############################################################################
#
# Declaration querying support

def ObjectSpecification(direct, cls):
    """Provide object specifications

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

    For example:

      >>> from zope.interface import Interface
      >>> class I1(Interface): pass
      ...
      >>> class I2(Interface): pass
      ...
      >>> class I3(Interface): pass
      ...
      >>> class I31(I3): pass
      ...
      >>> class I4(Interface): pass
      ...
      >>> class I5(Interface): pass
      ...
      >>> class A(object):
      ...     implements(I1)
      >>> class B(object): __implemented__ = I2
      ...
      >>> class C(A, B):
      ...     implements(I31)
      >>> c = C()
      >>> directlyProvides(c, I4)
      >>> [i.getName() for i in providedBy(c)]
      ['I4', 'I31', 'I1', 'I2']
      >>> [i.getName() for i in providedBy(c).flattened()]
      ['I4', 'I31', 'I3', 'I1', 'I2', 'Interface']
      >>> int(I1 in providedBy(c))
      1
      >>> int(I3 in providedBy(c))
      0
      >>> int(providedBy(c).extends(I3))
      1
      >>> int(providedBy(c).extends(I31))
      1
      >>> int(providedBy(c).extends(I5))
      0
      >>> class COnly(A, B):
      ...     implementsOnly(I31)
      >>> class D(COnly):
      ...     implements(I5)
      >>> c = D()
      >>> directlyProvides(c, I4)
      >>> [i.getName() for i in providedBy(c)]
      ['I4', 'I5', 'I31']
      >>> [i.getName() for i in providedBy(c).flattened()]
      ['I4', 'I5', 'I31', 'I3', 'Interface']
      >>> int(I1 in providedBy(c))
      0
      >>> int(I3 in providedBy(c))
      0
      >>> int(providedBy(c).extends(I3))
      1
      >>> int(providedBy(c).extends(I1))
      0
      >>> int(providedBy(c).extends(I31))
      1
      >>> int(providedBy(c).extends(I5))
      1
    """

    return Provides(cls, direct)

def getObjectSpecification(ob):

    provides = getattr(ob, '__provides__', None)
    if provides is not None:
        if isinstance(provides, SpecificationBase):
            return provides

    try:
        cls = ob.__class__
    except AttributeError:
        # We can't get the class, so just consider provides
        return _empty

    return implementedBy(cls)

def providedBy(ob):

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

    # Try to get __providedBy__
    try:
        r = ob.__providedBy__
    except AttributeError:
        # Not set yet. Fall back to lower-level thing that computes it
        return getObjectSpecification(ob)

    try:
        # We might have gotten a descriptor from an instance of a
        # class (like an ExtensionClass) that doesn't support
        # descriptors.  We'll make sure we got one by trying to get
        # the only attribute, which all specs have.
        r.extends

    except AttributeError:

        # The object's class doesn't understand descriptors.
        # Sigh. We need to get an object descriptor, but we have to be
        # careful.  We want to use the instance's __provides__, if
        # there is one, but only if it didn't come from the class.

        try:
            r = ob.__provides__
        except AttributeError:
            # No __provides__, so just fall back to implementedBy
            return implementedBy(ob.__class__)

        # We need to make sure we got the __provides__ from the
        # instance. We'll do this by making sure we don't get the same
        # thing from the class:

        try:
            cp = ob.__class__.__provides__
        except AttributeError:
            # The ob doesn't have a class or the class has no
            # provides, assume we're done:
            return r

        if r is cp:
            # Oops, we got the provides from the class. This means
            # the object doesn't have it's own. We should use implementedBy
            return implementedBy(ob.__class__)

    return r

class ObjectSpecificationDescriptorPy(object):
    """Implement the `__providedBy__` attribute

    The `__providedBy__` attribute computes the interfaces peovided by
    an object.
    """

    def __get__(self, inst, cls):
        """Get an object specification for an object

        For example:

          >>> from zope.interface import Interface
          >>> class IFoo(Interface): pass
          ...
          >>> class IFooFactory(Interface): pass
          ...
          >>> class C(object):
          ...   implements(IFoo)
          ...   classProvides(IFooFactory)
          >>> [i.getName() for i in C.__providedBy__]
          ['IFooFactory']
          >>> [i.getName() for i in C().__providedBy__]
          ['IFoo']

        """

        # Get an ObjectSpecification bound to either an instance or a class,
        # depending on how we were accessed.

        if inst is None:
            return getObjectSpecification(cls)

        provides = getattr(inst, '__provides__', None)
        if provides is not None:
            return provides

        return implementedBy(cls)

ObjectSpecificationDescriptor = ObjectSpecificationDescriptorPy

##############################################################################

def _normalizeargs(sequence, output = None):
    """Normalize declaration arguments

    Normalization arguments might contain Declarions, tuples, or single
    interfaces.

    Anything but individial interfaces or implements specs will be expanded.
    """
    if output is None:
        output = []

    cls = sequence.__class__
    if InterfaceClass in cls.__mro__ or Implements in cls.__mro__:
        output.append(sequence)
    else:
        for v in sequence:
            _normalizeargs(v, output)

    return output

_empty = Declaration()

try:
    import _zope_interface_coptimizations
except ImportError:
    pass
else:
    from _zope_interface_coptimizations import implementedBy, providedBy
    from _zope_interface_coptimizations import getObjectSpecification
    from _zope_interface_coptimizations import ObjectSpecificationDescriptor

objectSpecificationDescriptor = ObjectSpecificationDescriptor()