Debian Codegraph @

pypy/module/__builtin__/abstractinst.py

raw symbols SCIP
1 """
2 Implementation of the 'abstract instance and subclasses' protocol:
3 objects can return pseudo-classes as their '__class__' attribute, and
4 pseudo-classes can have a '__bases__' attribute with a tuple of other
5 pseudo-classes. The standard built-in functions isinstance() and
6 issubclass() follow and trust these attributes is they are present, in
7 addition to checking for instances and subtypes in the normal way.
8 """
9
10 from rpython.rlib import jit
11 from rpython.rlib.objectmodel import specialize
12
13 from pypy.interpreter.baseobjspace import ObjSpace as BaseObjSpace
14 from pypy.interpreter.error import OperationError, oefmt
15
16 def _get_bases(space, w_cls):
17 """Returns 'cls.__bases__'. Returns None if there is
18 no __bases__ or if cls.__bases__ is not a tuple.
19 """
20 try:
21 w_bases = space.getattr(w_cls, space.newtext('__bases__'))
22 except OperationError as e:
23 if not e.match(space, space.w_AttributeError):
24 raise # propagate other errors
25 return None
26 if space.isinstance_w(w_bases, space.w_tuple):
27 return w_bases
28 else:
29 return None
30
31 def abstract_isclass_w(space, w_obj):
32 return _get_bases(space, w_obj) is not None
33
34 @specialize.arg(2)
35 def check_class(space, w_obj, msg):
36 if not abstract_isclass_w(space, w_obj):
37 msg += ', got %T'
38 raise oefmt(space.w_TypeError, msg, w_obj)
39
40
41 def abstract_getclass(space, w_obj):
42 try:
43 return space.getattr(w_obj, space.newtext('__class__'))
44 except OperationError as e:
45 if not e.match(space, space.w_AttributeError):
46 raise # propagate other errors
47 return space.type(w_obj)
48
49
50 # ---------- isinstance ----------
51
52
53 def p_recursive_isinstance_w(space, w_inst, w_cls):
54 # Copied straight from CPython 2.7. Does not handle 'cls' being a tuple.
55 if space.isinstance_w(w_cls, space.w_type):
56 return p_recursive_isinstance_type_w(space, w_inst, w_cls)
57
58 check_class(space, w_cls, "isinstance() arg 2 must be a class, type,"
59 " or tuple of classes and types")
60 try:
61 w_abstractclass = space.getattr(w_inst, space.newtext('__class__'))
62 except OperationError as e:
63 if not e.match(space, space.w_AttributeError):
64 raise # propagate other errors
65 return False
66 else:
67 return p_abstract_issubclass_w(space, w_abstractclass, w_cls)
68
69
70 def p_recursive_isinstance_type_w(space, w_inst, w_type):
71 # subfunctionality of p_recursive_isinstance_w(): assumes that w_type is
72 # a type object. Copied straight from CPython 2.7.
73 if space.isinstance_w(w_inst, w_type):
74 return True
75 try:
76 w_abstractclass = space.getattr(w_inst, space.newtext('__class__'))
77 except OperationError as e:
78 if not e.match(space, space.w_AttributeError):
79 raise # propagate other errors
80 else:
81 if w_abstractclass is not space.type(w_inst):
82 if space.isinstance_w(w_abstractclass, space.w_type):
83 return space.issubtype_w(w_abstractclass, w_type)
84 return False
85
86
87 @jit.unroll_safe
88 def abstract_isinstance_w(space, w_obj, w_klass_or_tuple, allow_override=False):
89 """Implementation for the full 'isinstance(obj, klass_or_tuple)'."""
90 # Copied from CPython 2.7's PyObject_Isinstance(). Additionally,
91 # if 'allow_override' is False (the default), then don't try to
92 # use a custom __instancecheck__ method.
93
94 # WARNING: backward compatibility function name here. CPython
95 # uses the name "abstract" to refer to the logic of handling
96 # class-like objects, with a "__bases__" attribute. This function
97 # here is not related to that and implements the full
98 # PyObject_IsInstance() logic.
99
100 # Quick test for an exact match
101 if space.type(w_obj) is w_klass_or_tuple:
102 return True
103
104 # -- case (anything, tuple)
105 # XXX it might be risky that the JIT sees this
106 if space.isinstance_w(w_klass_or_tuple, space.w_tuple):
107 for w_klass in space.fixedview(w_klass_or_tuple):
108 if abstract_isinstance_w(space, w_obj, w_klass, allow_override):
109 return True
110 return False
111
112 # -- case (anything, type)
113 if allow_override:
114 w_check = space.lookup(w_klass_or_tuple, "__instancecheck__")
115 if w_check is not None:
116 # this is the common case: all type objects have a method
117 # __instancecheck__. The one in the base 'type' type calls
118 # back p_recursive_isinstance_type_w() from the present module.
119 return space.is_true(space.get_and_call_function(
120 w_check, w_klass_or_tuple, w_obj))
121
122 return p_recursive_isinstance_w(space, w_obj, w_klass_or_tuple)
123
124
125 # ---------- issubclass ----------
126
127
128 @jit.unroll_safe
129 def p_abstract_issubclass_w(space, w_derived, w_cls):
130 # Copied straight from CPython 2.7, function abstract_issubclass().
131 # Don't confuse this with the function abstract_issubclass_w() below.
132 # Here, w_cls cannot be a tuple.
133 while True:
134 if space.is_w(w_derived, w_cls):
135 return True
136 w_bases = _get_bases(space, w_derived)
137 if w_bases is None:
138 return False
139 bases_w = space.fixedview(w_bases)
140 last_index = len(bases_w) - 1
141 if last_index < 0:
142 return False
143 # Avoid recursivity in the single inheritance case; in general,
144 # don't recurse on the last item in the tuple (loop instead).
145 for i in range(last_index):
146 if p_abstract_issubclass_w(space, bases_w[i], w_cls):
147 return True
148 w_derived = bases_w[last_index]
149
150
151 def p_recursive_issubclass_w(space, w_derived, w_cls):
152 # From CPython's function of the same name (which as far as I can tell
153 # is not recursive). Copied straight from CPython 2.7.
154 if (space.isinstance_w(w_cls, space.w_type) and
155 space.isinstance_w(w_derived, space.w_type)):
156 return space.issubtype_w(w_derived, w_cls)
157 #
158 check_class(space, w_derived, "issubclass() arg 1 must be a class")
159 check_class(space, w_cls, "issubclass() arg 2 must be a class"
160 " or tuple of classes")
161 return p_abstract_issubclass_w(space, w_derived, w_cls)
162
163
164 @jit.unroll_safe
165 def abstract_issubclass_w(space, w_derived, w_klass_or_tuple,
166 allow_override=False):
167 """Implementation for the full 'issubclass(derived, klass_or_tuple)'."""
168
169 # WARNING: backward compatibility function name here. CPython
170 # uses the name "abstract" to refer to the logic of handling
171 # class-like objects, with a "__bases__" attribute. This function
172 # here is not related to that and implements the full
173 # PyObject_IsSubclass() logic. There is also p_abstract_issubclass_w().
174
175 # -- case (anything, tuple-of-classes)
176 if space.isinstance_w(w_klass_or_tuple, space.w_tuple):
177 for w_klass in space.fixedview(w_klass_or_tuple):
178 if abstract_issubclass_w(space, w_derived, w_klass, allow_override):
179 return True
180 return False
181
182 # -- case (anything, type)
183 if allow_override:
184 w_check = space.lookup(w_klass_or_tuple, "__subclasscheck__")
185 if w_check is not None:
186 # this is the common case: all type objects have a method
187 # __subclasscheck__. The one in the base 'type' type calls
188 # back p_recursive_issubclass_w() from the present module.
189 return space.is_true(space.get_and_call_function(
190 w_check, w_klass_or_tuple, w_derived))
191
192 return p_recursive_issubclass_w(space, w_derived, w_klass_or_tuple)
193
194
195 # ------------------------------------------------------------
196 # Exception helpers
197
198 def exception_is_valid_obj_as_class_w(space, w_obj):
199 return BaseObjSpace.exception_is_valid_obj_as_class_w(space, w_obj)
200
201 def exception_is_valid_class_w(space, w_cls):
202 return BaseObjSpace.exception_is_valid_class_w(space, w_cls)
203
204 def exception_getclass(space, w_obj):
205 return BaseObjSpace.exception_getclass(space, w_obj)
206
207 def exception_issubclass_w(space, w_cls1, w_cls2):
208 if (space.type(w_cls1) is space.w_type and
209 space.type(w_cls2) is space.w_type):
210 return BaseObjSpace.exception_issubclass_w(space, w_cls1, w_cls2)
211 #
212 if (not exception_is_valid_class_w(space, w_cls2) or
213 not exception_is_valid_class_w(space, w_cls1)):
214 return False
215 #
216 # The rest is the rare slow case. Use the general logic of issubclass()
217 # (issue #3149). CPython 3.x doesn't do that (but there is a
218 # many-years issue report: https://bugs.python.org/issue12029), and
219 # there are probably tests, so we won't call abstract_issubclass_w()
220 # either in PyPy3.
221 return BaseObjSpace.exception_issubclass_w(space, w_cls1, w_cls2)
222
223 # ____________________________________________________________
224 # App-level interface
225
226 def issubclass(space, w_cls, w_klass_or_tuple):
227 """Check whether a class 'cls' is a subclass (i.e., a derived class) of
228 another class. When using a tuple as the second argument, check whether
229 'cls' is a subclass of any of the classes listed in the tuple."""
230 result = abstract_issubclass_w(space, w_cls, w_klass_or_tuple, True)
231 return space.newbool(result)
232
233 def isinstance(space, w_obj, w_klass_or_tuple):
234 """Check whether an object is an instance of a class (or of a subclass
235 thereof). When using a tuple as the second argument, check whether 'obj'
236 is an instance of any of the classes listed in the tuple."""
237 result = abstract_isinstance_w(space, w_obj, w_klass_or_tuple, True)
238 return space.newbool(result)
239
240 # avoid namespace pollution
241 app_issubclass = issubclass; del issubclass
242 app_isinstance = isinstance; del isinstance