comparison mercurial/thirdparty/zope/interface/verify.py @ 37176:943d77fc07a3

thirdparty: vendor zope.interface 4.4.3 I've been trying to formalize interfaces for various components of Mercurial. So far, we've been using the "abc" package. This package is "good enough" for a lot of tasks. But it quickly falls over. For example, if you declare an @abc.abstractproperty, you must implement that attribute with a @property or the class compile time checking performed by abc will complain. This often forces you to implement dumb @property wrappers to return a _ prefixed attribute of the sane name. That's ugly. I've also wanted to implement automated checking that classes conform to various interfaces and don't expose other "public" attributes. After doing a bit of research and asking around, the general consensus seems to be that zope.interface is the best package for doing interface-based programming in Python. It has built-in support for verifying classes and objects conform to interfaces. It allows an interface's properties to be defined during __init__. There's even an "adapter registry" that allow you to register interfaces and look up which classes implement them. That could potentially be useful for places where our custom registry.py modules currently facilitates central registrations, but at a type level. Imagine extensions providing alternate implementations of things like the local repository interface to allow opening repositories with custom requirements. Anyway, this commit vendors zope.interface 4.4.3. The contents of the source tarball have been copied into mercurial/thirdparty/zope/ without modifications. Test modules have been removed because they are not interesting to us. The LICENSE.txt file has been copied so it lives next to the source. The Python modules don't use relative imports. zope/__init__.py defines a namespace package. So we'll need to modify the source code before this package is usable inside Mercurial. This will be done in subsequent commits. # no-check-commit for various style failures Differential Revision: https://phab.mercurial-scm.org/D2928
author Gregory Szorc <gregory.szorc@gmail.com>
date Wed, 21 Mar 2018 19:48:50 -0700
parents
children 68ee61822182
comparison
equal deleted inserted replaced
37175:fbe34945220d 37176:943d77fc07a3
1 ##############################################################################
2 #
3 # Copyright (c) 2001, 2002 Zope Foundation and Contributors.
4 # All Rights Reserved.
5 #
6 # This software is subject to the provisions of the Zope Public License,
7 # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
8 # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
9 # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
10 # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
11 # FOR A PARTICULAR PURPOSE.
12 #
13 ##############################################################################
14 """Verify interface implementations
15 """
16 from zope.interface.exceptions import BrokenImplementation, DoesNotImplement
17 from zope.interface.exceptions import BrokenMethodImplementation
18 from types import FunctionType, MethodType
19 from zope.interface.interface import fromMethod, fromFunction, Method
20 import sys
21
22 # This will be monkey-patched when running under Zope 2, so leave this
23 # here:
24 MethodTypes = (MethodType, )
25
26
27 def _verify(iface, candidate, tentative=0, vtype=None):
28 """Verify that 'candidate' might correctly implements 'iface'.
29
30 This involves:
31
32 o Making sure the candidate defines all the necessary methods
33
34 o Making sure the methods have the correct signature
35
36 o Making sure the candidate asserts that it implements the interface
37
38 Note that this isn't the same as verifying that the class does
39 implement the interface.
40
41 If optional tentative is true, suppress the "is implemented by" test.
42 """
43
44 if vtype == 'c':
45 tester = iface.implementedBy
46 else:
47 tester = iface.providedBy
48
49 if not tentative and not tester(candidate):
50 raise DoesNotImplement(iface)
51
52 # Here the `desc` is either an `Attribute` or `Method` instance
53 for name, desc in iface.namesAndDescriptions(1):
54 try:
55 attr = getattr(candidate, name)
56 except AttributeError:
57 if (not isinstance(desc, Method)) and vtype == 'c':
58 # We can't verify non-methods on classes, since the
59 # class may provide attrs in it's __init__.
60 continue
61
62 raise BrokenImplementation(iface, name)
63
64 if not isinstance(desc, Method):
65 # If it's not a method, there's nothing else we can test
66 continue
67
68 if isinstance(attr, FunctionType):
69 if sys.version_info[0] >= 3 and isinstance(candidate, type):
70 # This is an "unbound method" in Python 3.
71 meth = fromFunction(attr, iface, name=name,
72 imlevel=1)
73 else:
74 # Nope, just a normal function
75 meth = fromFunction(attr, iface, name=name)
76 elif (isinstance(attr, MethodTypes)
77 and type(attr.__func__) is FunctionType):
78 meth = fromMethod(attr, iface, name)
79 elif isinstance(attr, property) and vtype == 'c':
80 # We without an instance we cannot be sure it's not a
81 # callable.
82 continue
83 else:
84 if not callable(attr):
85 raise BrokenMethodImplementation(name, "Not a method")
86 # sigh, it's callable, but we don't know how to introspect it, so
87 # we have to give it a pass.
88 continue
89
90 # Make sure that the required and implemented method signatures are
91 # the same.
92 desc = desc.getSignatureInfo()
93 meth = meth.getSignatureInfo()
94
95 mess = _incompat(desc, meth)
96 if mess:
97 raise BrokenMethodImplementation(name, mess)
98
99 return True
100
101 def verifyClass(iface, candidate, tentative=0):
102 return _verify(iface, candidate, tentative, vtype='c')
103
104 def verifyObject(iface, candidate, tentative=0):
105 return _verify(iface, candidate, tentative, vtype='o')
106
107 def _incompat(required, implemented):
108 #if (required['positional'] !=
109 # implemented['positional'][:len(required['positional'])]
110 # and implemented['kwargs'] is None):
111 # return 'imlementation has different argument names'
112 if len(implemented['required']) > len(required['required']):
113 return 'implementation requires too many arguments'
114 if ((len(implemented['positional']) < len(required['positional']))
115 and not implemented['varargs']):
116 return "implementation doesn't allow enough arguments"
117 if required['kwargs'] and not implemented['kwargs']:
118 return "implementation doesn't support keyword arguments"
119 if required['varargs'] and not implemented['varargs']:
120 return "implementation doesn't support variable arguments"