Debian Codegraph @

pypy/module/cpyext/test/test_typeobject.py

raw symbols SCIP
1 import pytest
2 from pypy.interpreter import gateway
3 from rpython.rtyper.lltypesystem import rffi
4 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
5 from pypy.module.cpyext.test.test_api import BaseApiTest
6 from pypy.module.cpyext.api import generic_cpy_call
7 from pypy.module.cpyext.pyobject import make_ref, from_ref, decref, as_pyobj
8 from pypy.module.cpyext.typeobject import cts, PyTypeObjectPtr, W_PyCTypeObject
9
10
11
12 class AppTestTypeObject(AppTestCpythonExtensionBase):
13
14 def setup_class(cls):
15 AppTestCpythonExtensionBase.setup_class.im_func(cls)
16 def _check_uses_shortcut(w_inst):
17 res = hasattr(w_inst, "_cpy_ref") and w_inst._cpy_ref
18 res = res and as_pyobj(cls.space, w_inst) == w_inst._cpy_ref
19 return cls.space.newbool(res)
20 cls.w__check_uses_shortcut = cls.space.wrap(
21 gateway.interp2app(_check_uses_shortcut))
22
23 def test_typeobject(self):
24 import sys
25 module = self.import_module(name='foo')
26 assert 'foo' in sys.modules
27 assert "copy" in dir(module.fooType)
28 obj = module.new()
29 #print(obj.foo)
30 assert obj.foo == 42
31 #print("Obj has type", type(obj))
32 assert type(obj) is module.fooType
33 #print("type of obj has type", type(type(obj)))
34 #print("type of type of obj has type", type(type(type(obj))))
35 assert module.fooType.__doc__ == "foo is for testing."
36
37 def test_typeobject_method_descriptor(self):
38 module = self.import_module(name='foo')
39 obj = module.new()
40 obj2 = obj.copy()
41 assert module.new().name == "Foo Example"
42 c = module.fooType.copy
43 assert not "im_func" in dir(module.fooType.copy)
44 assert module.fooType.copy.__objclass__ is module.fooType
45 assert "copy" in repr(module.fooType.copy)
46 assert repr(module.fooType) == "<class 'foo.foo'>"
47 assert repr(obj2) == "<Foo>"
48 assert repr(module.fooType.__call__) == "<slot wrapper '__call__' of 'foo.foo' objects>"
49 assert obj2(foo=1, bar=2) == dict(foo=1, bar=2)
50 assert module.fooType.__repr__.__text_signature__ == '($self, /)'
51
52 print(obj.foo)
53 assert obj.foo == 42
54 assert obj.int_member == obj.foo
55
56 def test_typeobject_data_member(self):
57 module = self.import_module(name='foo')
58 obj = module.new()
59 obj.int_member = 23
60 assert obj.int_member == 23
61 obj.int_member = 42
62 raises(TypeError, "obj.int_member = 'not a number'")
63 raises(TypeError, "del obj.int_member")
64 raises(AttributeError, "obj.int_member_readonly = 42")
65 exc = raises(AttributeError, "del obj.int_member_readonly")
66 assert "readonly" in str(exc.value)
67 raises(SystemError, "obj.broken_member")
68 raises(SystemError, "obj.broken_member = 42")
69 assert module.fooType.broken_member.__doc__ is None
70 assert module.fooType.object_member.__doc__ == "A Python object."
71 assert str(type(module.fooType.int_member)) == "<class 'member_descriptor'>"
72
73 def test_typeobject_object_member(self):
74 module = self.import_module(name='foo')
75 obj = module.new()
76 assert obj.object_member is None
77 obj.object_member = "hello"
78 assert obj.object_member == "hello"
79 del obj.object_member
80 # Make sure a second call does not fail
81 del obj.object_member
82 assert obj.object_member is None
83 raises(AttributeError, "obj.object_member_ex")
84 obj.object_member_ex = None
85 assert obj.object_member_ex is None
86 obj.object_member_ex = 42
87 assert obj.object_member_ex == 42
88 del obj.object_member_ex
89 raises(AttributeError, "del obj.object_member_ex")
90
91 obj.set_foo = 32
92 assert obj.foo == 32
93
94 def test_typeobject_string_member(self):
95 module = self.import_module(name='foo')
96 obj = module.new()
97 assert obj.string_member == "Hello from PyPy"
98 raises(TypeError, "obj.string_member = 42")
99 raises(TypeError, "del obj.string_member")
100 obj.unset_string_member()
101 assert obj.string_member is None
102 assert obj.string_member_inplace == "spam"
103 raises(TypeError, "obj.string_member_inplace = 42")
104 raises(TypeError, "del obj.string_member_inplace")
105 assert obj.char_member == "s"
106 obj.char_member = "a"
107 assert obj.char_member == "a"
108 raises(TypeError, "obj.char_member = 'spam'")
109 raises(TypeError, "obj.char_member = 42")
110 #
111
112 def test_typeobject_int_member(self):
113 import sys, struct
114 module = self.import_module(name='foo')
115 obj = module.new()
116 max_uint = struct.unpack_from("@L", b"\xFF" * 8)[0]
117 bignum = max_uint//2 - 42
118 obj.short_member = -12345; assert obj.short_member == -12345
119 obj.long_member = -bignum; assert obj.long_member == -bignum
120 obj.ushort_member = 45678; assert obj.ushort_member == 45678
121 obj.uint_member = 3000000000; assert obj.uint_member == 3000000000
122 obj.ulong_member = 2*bignum; assert obj.ulong_member == 2*bignum
123 obj.byte_member = -99; assert obj.byte_member == -99
124 obj.ubyte_member = 199; assert obj.ubyte_member == 199
125 obj.bool_member = True; assert obj.bool_member is True
126 obj.float_member = 9.25; assert obj.float_member == 9.25
127 obj.double_member = 9.25; assert obj.double_member == 9.25
128 obj.longlong_member = -2**59; assert obj.longlong_member == -2**59
129 obj.ulonglong_member = 2**63; assert obj.ulonglong_member == 2**63
130 obj.ssizet_member = sys.maxsize;assert obj.ssizet_member == sys.maxsize
131 #
132 obj.ulong_member = -3; assert obj.ulong_member == max_uint + 1 - 3, obj.ulong_member
133
134 def test_int_member_index_protocol(self):
135 # T_ULONG should accept objects implementing __index__, like T_UINT does
136 module = self.import_module(name='foo')
137 obj = module.new()
138 class Index:
139 def __init__(self, val): self.val = val
140 def __index__(self): return self.val
141 obj.uint_member = Index(42)
142 assert obj.uint_member == 42
143 obj.ulong_member = Index(99)
144 assert obj.ulong_member == 99
145 # T_PYSSIZET must NOT accept __index__ objects - plain int only
146 raises(TypeError, setattr, obj, 'ssizet_member', Index(1))
147
148 def test_overflow(self):
149 import struct, warnings
150 module = self.import_module(name='foo')
151 obj = module.new()
152 nbits_short = len(struct.pack("H", 0)) * 8 - 1
153 shrt_min = -2 ** nbits_short
154 with raises(OverflowError) as e:
155 obj.ushort_member = -2**63 - 1
156 assert "int too large to convert to C" in str(e.value)
157 with warnings.catch_warnings(record=True) as w:
158 warnings.simplefilter("always", RuntimeWarning)
159 obj.ushort_member = shrt_min - 100
160 assert len(w) == 1
161 assert "runcation of value" in str(w[0]), str(w[0])
162
163 def test_staticmethod(self):
164 module = self.import_module(name="foo")
165 obj = module.fooType.create()
166 assert obj.foo == 42
167 obj2 = obj.create()
168 assert obj2.foo == 42
169 assert obj2.create.__qualname__ == "foo.create"
170
171 def test_classmethod(self):
172 module = self.import_module(name="foo")
173 classmeth = module.fooType.classmeth
174 assert classmeth.__qualname__ == "foo.classmeth"
175 obj = classmeth()
176 assert obj is module.fooType
177 class _C:
178 def _m(self): pass
179 MethodType = type(_C()._m)
180 assert not isinstance(classmeth, MethodType)
181 assert classmeth.__doc__ is None
182 assert classmeth.__text_signature__ is None
183
184 def test_class_getitem(self):
185 module = self.import_module(name='foo')
186 f = module.fooType.__class_getitem__
187 print(dir(f))
188 assert f.__qualname__ == "foo.__class_getitem__"
189 out = f(42)
190 assert str(out) == 'foo.foo[42]'
191 assert f.__doc__ == "See PEP 585"
192 assert f.__text_signature__ == '($type, x, /)'
193
194 def test_methoddescr(self):
195 module = self.import_module(name='foo')
196 descr = module.fooType.copy
197 print(descr.__qualname__)
198 assert descr.__qualname__ == "foo.copy"
199 assert type(descr).__name__ == 'method_descriptor'
200 assert str(descr) in ("<method 'copy' of 'foo.foo' objects>",
201 "<method 'copy' of 'foo' objects>")
202 assert repr(descr) in ("<method 'copy' of 'foo.foo' objects>",
203 "<method 'copy' of 'foo' objects>")
204 raises(TypeError, descr, None)
205 assert descr.__doc__ == "Copy the foo."
206 assert descr.__text_signature__ == '($self, /)'
207 import inspect
208 assert not inspect.isbuiltin(descr)
209 assert inspect.ismethoddescriptor(descr)
210
211 def test_cython_fake_classmethod(self):
212 module = self.import_module(name='foo')
213
214 # Check that objects are printable
215 print(module.fooType.fake_classmeth) # bound method on the class
216 print(module.fooType.__dict__['fake_classmeth']) # raw descriptor
217
218 assert module.fooType.fake_classmeth() is module.fooType
219
220 def test_new(self):
221 # XXX cpython segfaults but if run singly (with -k test_new) this passes
222 module = self.import_module(name='foo')
223 obj = module.new()
224 # call __new__
225 newobj = module.UnicodeSubtype(u"xyz")
226 assert newobj == u"xyz"
227 assert isinstance(newobj, module.UnicodeSubtype)
228
229 assert isinstance(module.fooType(), module.fooType)
230 class bar(module.fooType):
231 pass
232 assert isinstance(bar(), bar)
233
234 fuu = module.UnicodeSubtype
235 class fuu2(fuu):
236 def baz(self):
237 return self
238 assert fuu2(u"abc").baz().escape()
239 raises(TypeError, module.fooType.object_member.__get__, 1)
240
241 def test_shortcut(self):
242 # test that instances of classes that are defined in C become an
243 # instance of W_BaseCPyObject and thus can be converted faster back to
244 # their pyobj, because they store a pointer to it directly.
245 if self.runappdirect:
246 skip("can't run with -A")
247 module = self.import_module(name='foo')
248 obj = module.fooType()
249 assert self._check_uses_shortcut(obj)
250 # W_TypeObjects use shortcut
251 assert self._check_uses_shortcut(object)
252 assert self._check_uses_shortcut(type)
253 # None, True, False use shortcut
254 assert self._check_uses_shortcut(None)
255 assert self._check_uses_shortcut(True)
256 assert self._check_uses_shortcut(False)
257 assert not self._check_uses_shortcut(1)
258 assert not self._check_uses_shortcut(object())
259
260 def test_multiple_inheritance1(self):
261 module = self.import_module(name='foo')
262 obj = module.UnicodeSubtype(u'xyz')
263 obj2 = module.UnicodeSubtype2()
264 obj3 = module.UnicodeSubtype3()
265 assert obj3.get_val() == 42
266 assert len(type(obj3).mro()) == 5
267
268 def test_init(self):
269 module = self.import_module(name="foo")
270 newobj = module.UnicodeSubtype()
271 assert newobj.get_val() == 42
272
273 # this subtype should inherit tp_init
274 newobj = module.UnicodeSubtype2()
275 assert newobj.get_val() == 42
276
277 # this subclass redefines __init__
278 class UnicodeSubclass2(module.UnicodeSubtype):
279 def __init__(self):
280 self.foobar = 32
281 super(UnicodeSubclass2, self).__init__()
282
283 newobj = UnicodeSubclass2()
284 assert newobj.get_val() == 42
285 assert newobj.foobar == 32
286
287 def test_metatype(self):
288 module = self.import_module(name='foo')
289 assert module.MetaType.__mro__ == (module.MetaType, type, object)
290 x = module.MetaType('name', (), {})
291 assert isinstance(x, type)
292 assert isinstance(x, module.MetaType)
293 x()
294
295 def test_metaclass_compatible(self):
296 # metaclasses should not conflict here
297 module = self.import_module(name='foo')
298 assert module.MetaType.__mro__ == (module.MetaType, type, object)
299 assert type(module.fooType).__mro__ == (type, object)
300 y = module.MetaType('other', (module.MetaType,), {})
301 assert isinstance(y, module.MetaType)
302 x = y('something', (type(y),), {})
303 del x, y
304
305 def test_metaclass_compatible2(self):
306 skip('fails even with -A, fooType has BASETYPE flag')
307 # XXX FIX - must raise since fooType (which is a base type)
308 # does not have flag Py_TPFLAGS_BASETYPE
309 module = self.import_module(name='foo')
310 raises(TypeError, module.MetaType, 'other', (module.fooType,), {})
311
312 def test_init_error(self):
313 module = self.import_module("foo")
314 raises(ValueError, module.InitErrType)
315
316 def test_cmps(self):
317 module = self.import_module("comparisons")
318 cmpr = module.CmpType()
319 assert cmpr == 3
320 assert cmpr != 42
321
322 def test_richcompare(self):
323 module = self.import_module("comparisons")
324 cmpr = module.CmpType()
325
326 # should not crash
327 raises(TypeError, "cmpr < 4")
328 raises(TypeError, "cmpr <= 4")
329 raises(TypeError, "cmpr > 4")
330 raises(TypeError, "cmpr >= 4")
331
332 assert cmpr.__le__(4) is NotImplemented
333
334 def test_hash(self):
335 module = self.import_module("comparisons")
336 cmpr = module.CmpType()
337 assert hash(cmpr) == 3
338 d = {}
339 d[cmpr] = 72
340 assert d[cmpr] == 72
341 assert d[3] == 72
342
343 def test_hash_inheritance(self):
344 foo = self.import_module("foo")
345 assert hash(foo.UnicodeSubtype(u'xyz')) == hash(u'xyz')
346 assert foo.UnicodeSubtype.__hash__ is str.__hash__
347 assert hash(foo.UnicodeSubtype3(u'xyz')) == hash(u'xyz')
348 assert foo.UnicodeSubtype3.__hash__ is str.__hash__
349
350 def test_descriptor(self):
351 module = self.import_module("foo")
352 prop = module.Property()
353 class C(object):
354 x = prop
355 obj = C()
356 assert obj.x == (prop, obj, C)
357 assert C.x == (prop, None, C)
358
359 obj.x = 2
360 assert obj.y == (prop, 2)
361 del obj.x
362 assert obj.z == prop
363
364 def test_tp_dict(self):
365 foo = self.import_module("foo")
366 module = self.import_extension('test', [
367 ("read_tp_dict", "METH_O",
368 '''
369 PyObject *method;
370 if (!args->ob_type->tp_dict)
371 {
372 PyErr_SetNone(PyExc_ValueError);
373 return NULL;
374 }
375 method = PyDict_GetItemString(
376 args->ob_type->tp_dict, "copy");
377 Py_INCREF(method);
378 return method;
379 '''),
380 ("get_type_dict", "METH_O",
381 '''
382 PyObject* value = args->ob_type->tp_dict;
383 if (value == NULL) value = Py_None;
384 Py_INCREF(value);
385 return value;
386 '''),
387 ])
388 obj = foo.new()
389 assert module.read_tp_dict(obj) == foo.fooType.copy
390 d = module.get_type_dict(obj)
391 assert type(d) is dict
392 d["_some_attribute"] = 1
393 assert type(obj)._some_attribute == 1
394 del d["_some_attribute"]
395
396 class A(object):
397 pass
398 obj = A()
399 d = module.get_type_dict(obj)
400 assert type(d) is dict
401 d["_some_attribute"] = 1
402 assert type(obj)._some_attribute == 1
403 del d["_some_attribute"]
404
405 d = module.get_type_dict(1)
406 assert type(d) is dict
407 try:
408 d["_some_attribute"] = 1
409 except TypeError: # on PyPy, int.__dict__ is really immutable
410 pass
411 else:
412 assert int._some_attribute == 1
413 del d["_some_attribute"]
414
415 def test_custom_allocation(self):
416 foo = self.import_module("foo")
417 obj = foo.newCustom()
418 assert type(obj) is foo.Custom
419 assert type(foo.Custom) is foo.MetaType
420
421 def test_heaptype(self):
422 module = self.import_extension('foo', [
423 ("name_by_heaptype", "METH_O",
424 '''
425 PyHeapTypeObject *heaptype = (PyHeapTypeObject *)args;
426 Py_INCREF(heaptype->ht_name);
427 return heaptype->ht_name;
428 '''),
429 ("setattr", "METH_O",
430 '''
431 int ret;
432 PyObject* name = PyBytes_FromString("mymodule");
433 PyObject *obj = PyType_Type.tp_alloc(&PyType_Type, 0);
434 PyHeapTypeObject *type = (PyHeapTypeObject*)obj;
435 /* this is issue #2434: logic from pybind11 */
436 type->ht_type.tp_flags |= Py_TPFLAGS_HEAPTYPE;
437 type->ht_type.tp_name = ((PyTypeObject*)args)->tp_name;
438 type->ht_name = PyUnicode_FromString(type->ht_type.tp_name);
439 PyType_Ready(&type->ht_type);
440 ret = PyObject_SetAttrString((PyObject*)&type->ht_type,
441 "__module__", name);
442 Py_DECREF(name);
443 if (ret < 0)
444 return NULL;
445 return PyLong_FromLong(ret);
446 '''),
447 ])
448 class C(object):
449 pass
450 assert module.name_by_heaptype(C) == "C"
451 assert module.setattr(C) == 0
452
453
454 def test_type_dict(self):
455 foo = self.import_module("foo")
456 module = self.import_extension('test', [
457 ("hack_tp_dict", "METH_VARARGS",
458 '''
459 PyTypeObject *type;
460 PyObject *a1 = PyLong_FromLong(1);
461 PyObject *a2 = PyLong_FromLong(2);
462 PyObject *obj, *value, *key;
463 if (!PyArg_ParseTuple(args, "OO", &obj, &key))
464 return NULL;
465 type = obj->ob_type;
466
467 if (PyDict_SetItem(type->tp_dict, key,
468 a1) < 0)
469 return NULL;
470 Py_DECREF(a1);
471 PyType_Modified(type);
472 value = PyObject_GetAttr((PyObject *)type, key);
473 Py_DECREF(value);
474
475 if (PyDict_SetItem(type->tp_dict, key,
476 a2) < 0)
477 return NULL;
478 Py_DECREF(a2);
479 PyType_Modified(type);
480 value = PyObject_GetAttr((PyObject *)type, key);
481 return value;
482 '''
483 )
484 ])
485 obj = foo.new()
486 assert module.hack_tp_dict(obj, "a") == 2
487 class Sub(foo.fooType):
488 pass
489 obj = Sub()
490 assert module.hack_tp_dict(obj, "b") == 2
491
492
493 def test_tp_dict_ready(self):
494 module = self.import_extension('foo', [
495 ("new_obj", "METH_NOARGS",
496 '''
497 PyObject *obj;
498 obj = PyObject_New(PyObject, &Foo_Type);
499 return obj;
500 '''
501 )], prologue='''
502 static PyTypeObject Foo_Type = {
503 PyVarObject_HEAD_INIT(NULL, 0)
504 "foo.foo",
505 };
506 ''', more_init = '''
507 Foo_Type.tp_flags = Py_TPFLAGS_DEFAULT;
508 Foo_Type.tp_dict = PyDict_New();
509 PyDict_SetItemString(Foo_Type.tp_dict, "inserted", Py_True);
510 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
511 ''')
512
513 obj = module.new_obj()
514 assert type(obj).inserted is True
515
516
517 def test_tp_descr_get(self):
518 module = self.import_extension('foo', [
519 ("tp_descr_get", "METH_O",
520 '''
521 if (args->ob_type->tp_descr_get == NULL) {
522 Py_INCREF(Py_False);
523 return Py_False;
524 }
525 return args->ob_type->tp_descr_get(args, NULL,
526 (PyObject *)&PyLong_Type);
527 '''
528 )
529 ])
530 assert module.tp_descr_get(42) is False
531
532 class Y(object):
533 def __get__(self, *args):
534 return 42
535 def unbound_method_example(self):
536 pass
537 assert module.tp_descr_get(Y()) == 42
538 #
539 p = property(lambda self: 42)
540 result = module.tp_descr_get(p)
541 assert result is p
542 #
543 f = lambda x: x + 1
544 ubm = module.tp_descr_get(f)
545 assert type(ubm) is type(Y.unbound_method_example)
546 assert ubm(42) == 43
547
548 def test_tp_descr_set(self):
549 module = self.import_extension('foo', [
550 ("tp_descr_set", "METH_O",
551 '''
552 if (args->ob_type->tp_descr_set == NULL) {
553 Py_INCREF(Py_False);
554 return Py_False;
555 }
556 if (args->ob_type->tp_descr_set(args, Py_False, Py_True) != 0)
557 return NULL;
558 if (args->ob_type->tp_descr_set(args, Py_Ellipsis, NULL) != 0)
559 return NULL;
560
561 Py_INCREF(Py_True);
562 return Py_True;
563 '''
564 )
565 ])
566 assert module.tp_descr_set(42) is False
567
568 class Y(object):
569 def __set__(self, obj, value):
570 assert obj is False
571 assert value is True
572 def __delete__(self, obj):
573 assert obj is Ellipsis
574 assert module.tp_descr_set(Y()) is True
575 #
576 def pset(obj, value):
577 assert obj is False
578 assert value is True
579 def pdel(obj):
580 assert obj is Ellipsis
581 p = property(lambda: "never used", pset, pdel)
582 assert module.tp_descr_set(p) is True
583
584 def test_signature_and_attributes(self):
585 import sys
586 mod = self.import_module(name='docstrings')
587 assert mod.no_doc.__doc__ is None
588 assert mod.no_doc.__text_signature__ is None
589 assert mod.empty_doc.__doc__ is None
590 assert mod.empty_doc.__text_signature__ is None
591 assert mod.no_sig.__doc__
592 assert mod.no_sig.__text_signature__ is None
593 assert mod.invalid_sig.__doc__
594 assert mod.invalid_sig.__text_signature__ is None
595 assert mod.invalid_sig2.__doc__
596 assert mod.invalid_sig2.__text_signature__ is None
597 assert mod.with_sig.__doc__
598 assert mod.with_sig.__text_signature__ == '($module, /, sig)'
599 assert mod.with_sig_but_no_doc.__doc__ is None
600 assert mod.with_sig_but_no_doc.__text_signature__ == '($module, /, sig)'
601 assert mod.with_signature_and_extra_newlines.__doc__
602 assert (mod.with_signature_and_extra_newlines.__text_signature__ ==
603 '($module, /, parameter)')
604
605 htype = mod.HeapType
606 assert htype().__doc__ == "A type with a signature"
607 assert mod.SomeType.__text_signature__ == '()'
608 assert mod.SomeType.__doc__ == 'A type with a signature'
609 assert htype.__text_signature__ == '()'
610
611 assert htype.__module__ == 'docstrings'
612 assert htype.__name__ == 'HeapType'
613 assert htype.__qualname__ == 'HeapType'
614
615
616 class TestTypes(BaseApiTest):
617 def test_type_attributes(self, space, api):
618 w_class = space.appexec([], """():
619 class A(object):
620 pass
621 return A
622 """)
623 ref = make_ref(space, w_class)
624
625 py_type = rffi.cast(PyTypeObjectPtr, ref)
626 assert py_type.c_tp_alloc
627 w_tup = from_ref(space, py_type.c_tp_mro)
628 assert space.fixedview(w_tup) == w_class.mro_w
629
630 decref(space, ref)
631
632 def test_type_dict(self, space, api):
633 w_class = space.appexec([], """():
634 class A(object):
635 pass
636 return A
637 """)
638 ref = make_ref(space, w_class)
639
640 py_type = rffi.cast(PyTypeObjectPtr, ref)
641 w_dict = from_ref(space, py_type.c_tp_dict)
642 w_name = space.newtext('a')
643 space.setitem(w_dict, w_name, space.wrap(1))
644 assert space.int_w(space.getattr(w_class, w_name)) == 1
645 space.delitem(w_dict, w_name)
646
647 def test_multiple_inheritance2(self, space, api):
648 w_class = space.appexec([], """():
649 class A(object):
650 pass
651 class B(object):
652 pass
653 class C(A, B):
654 pass
655 return C
656 """)
657 ref = make_ref(space, w_class)
658 decref(space, ref)
659
660 def test_lookup(self, space, api):
661 w_type = space.w_bytes
662 w_obj = api._PyType_Lookup(w_type, space.wrap("upper"))
663 assert space.is_w(w_obj, space.w_bytes.getdictvalue(space, "upper"))
664
665 w_obj = api._PyType_Lookup(w_type, space.wrap("__invalid"))
666 assert w_obj is None
667 assert api.PyErr_Occurred() is None
668
669 def test_typeslots(self, space):
670 assert cts.macros['Py_tp_doc'] == 56
671
672 def test_subclass_not_PyCTypeObject(self, space, api):
673 pyobj = make_ref(space, api.PyLong_Type)
674 py_type = rffi.cast(PyTypeObjectPtr, pyobj)
675 w_pyclass = W_PyCTypeObject(space, py_type)
676 w_class = space.appexec([w_pyclass], """(base):
677 class Sub(base):
678 def addattrib(self, value):
679 self.attrib = value
680 return Sub
681 """)
682 assert w_pyclass in w_class.mro_w
683 assert isinstance(w_pyclass, W_PyCTypeObject)
684 assert not isinstance(w_class, W_PyCTypeObject)
685 assert w_pyclass.is_cpytype()
686 # XXX document the current status, not clear if this is desirable
687 assert w_class.is_cpytype()
688
689
690 class AppTestSlots(AppTestCpythonExtensionBase):
691 def setup_class(cls):
692 AppTestCpythonExtensionBase.setup_class.im_func(cls)
693 def _check_type_object(w_X):
694 assert w_X.is_cpytype()
695 assert not w_X.is_heaptype()
696 cls.w__check_type_object = cls.space.wrap(
697 gateway.interp2app(_check_type_object))
698
699 def test_some_slots(self):
700 module = self.import_extension('foo', [
701 ("test_type", "METH_O",
702 '''
703 /* "args->ob_type" is a strange way to get at 'type',
704 which should have a different tp_getattro/tp_setattro
705 than its tp_base, which is 'object'.
706 */
707
708 if (!args->ob_type->tp_setattro)
709 {
710 PyErr_SetString(PyExc_ValueError, "missing tp_setattro");
711 return NULL;
712 }
713 if (args->ob_type->tp_setattro ==
714 args->ob_type->tp_base->tp_setattro)
715 {
716 /* Note that unlike CPython, in PyPy 'type.tp_setattro'
717 is the same function as 'object.tp_setattro'. This
718 test used to check that it was not, but that was an
719 artifact of the bootstrap logic only---in the final
720 C sources I checked and they are indeed the same.
721 So we ignore this problem here. */
722 }
723 if (!args->ob_type->tp_getattro)
724 {
725 PyErr_SetString(PyExc_ValueError, "missing tp_getattro");
726 return NULL;
727 }
728 if (args->ob_type->tp_getattro ==
729 args->ob_type->tp_base->tp_getattro)
730 {
731 PyErr_SetString(PyExc_ValueError, "recursive tp_getattro");
732 return NULL;
733 }
734 Py_RETURN_TRUE;
735 '''
736 )
737 ])
738 assert module.test_type(type(None))
739
740 def test_tp_getattro(self):
741 module = self.import_extension('foo', [
742 ("test_tp_getattro", "METH_VARARGS",
743 '''
744 #if PY_MAJOR_VERSION > 2
745 #define PyString_FromString PyUnicode_FromString
746 #define PyIntObject PyLongObject
747 #define PyInt_AsLong PyLong_AsLong
748 #endif
749 PyObject *name, *obj = PyTuple_GET_ITEM(args, 0);
750 PyObject *attr, *value = PyTuple_GET_ITEM(args, 1);
751 if (!obj->ob_type->tp_getattro)
752 {
753 PyErr_SetString(PyExc_ValueError, "missing tp_getattro");
754 return NULL;
755 }
756 name = PyString_FromString("attr1");
757 attr = obj->ob_type->tp_getattro(obj, name);
758 if (PyInt_AsLong(attr) != PyInt_AsLong(value))
759 {
760 PyErr_SetString(PyExc_ValueError,
761 "tp_getattro returned wrong value");
762 return NULL;
763 }
764 Py_DECREF(name);
765 Py_DECREF(attr);
766 name = PyString_FromString("attr2");
767 attr = obj->ob_type->tp_getattro(obj, name);
768 if (attr == NULL && PyErr_ExceptionMatches(PyExc_AttributeError))
769 {
770 PyErr_Clear();
771 } else {
772 PyErr_SetString(PyExc_ValueError,
773 "tp_getattro should have raised");
774 return NULL;
775 }
776 Py_DECREF(name);
777 Py_RETURN_TRUE;
778 '''
779 )
780 ])
781 class C:
782 def __init__(self):
783 self.attr1 = 123
784 assert module.test_tp_getattro(C(), 123)
785
786 def test_issue_2760_getattr(self):
787 module = self.import_extension('foo', [
788 ("get_foo", "METH_O",
789 '''
790 #if PY_MAJOR_VERSION > 2
791 #define PyString_FromString PyUnicode_FromString
792 #endif
793 char* name = "foo";
794 PyTypeObject *tp = Py_TYPE(args);
795 PyObject *res;
796 if (tp->tp_getattr != NULL) {
797 res = (*tp->tp_getattr)(args, name);
798 }
799 else if (tp->tp_getattro != NULL) {
800 PyObject *w = PyString_FromString(name);
801 res = (*tp->tp_getattro)(args, w);
802 Py_DECREF(w);
803 }
804 else {
805 res = Py_None;
806 }
807 return res;
808 ''')])
809 class Passthrough(object):
810 def __getattr__(self, name):
811 return name
812
813 obj = Passthrough()
814 assert module.get_foo(obj) == 'foo'
815
816 def test_nb_int(self):
817 module = self.import_extension('foo', [
818 ("nb_int", "METH_VARARGS",
819 '''
820 PyTypeObject *type = (PyTypeObject *)PyTuple_GET_ITEM(args, 0);
821 PyObject *obj = PyTuple_GET_ITEM(args, 1);
822 if (!type->tp_as_number ||
823 !type->tp_as_number->nb_int)
824 {
825 PyErr_SetNone(PyExc_ValueError);
826 return NULL;
827 }
828 return type->tp_as_number->nb_int(obj);
829 '''
830 )
831 ])
832 assert module.nb_int(int, 10) == 10
833 assert module.nb_int(float, -12.3) == -12
834 raises(ValueError, module.nb_int, str, "123")
835 class F(float):
836 def __int__(self):
837 return 666
838 expected = float.__int__(F(-12.3))
839 assert module.nb_int(float, F(-12.3)) == expected
840 assert module.nb_int(F, F(-12.3)) == 666
841 class A:
842 pass
843 raises(ValueError, module.nb_int, A, A())
844
845 def test_nb_float(self):
846 module = self.import_extension('foo', [
847 ("nb_float", "METH_VARARGS",
848 '''
849 PyTypeObject *type = (PyTypeObject *)PyTuple_GET_ITEM(args, 0);
850 PyObject *obj = PyTuple_GET_ITEM(args, 1);
851 if (!type->tp_as_number ||
852 !type->tp_as_number->nb_float)
853 {
854 PyErr_SetNone(PyExc_ValueError);
855 return NULL;
856 }
857 return type->tp_as_number->nb_float(obj);
858 '''
859 )
860 ])
861 assert module.nb_float(int, 10) == 10.0
862 assert module.nb_float(float, -12.3) == -12.3
863 raises(ValueError, module.nb_float, str, "123")
864 #
865 # check that calling PyInt_Type->tp_as_number->nb_float(x)
866 # does not invoke a user-defined __float__()
867 class I(int):
868 def __float__(self):
869 return -55.55
870 class F(float):
871 def __float__(self):
872 return -66.66
873 assert float(I(10)) == -55.55
874 assert float(F(10.5)) == -66.66
875 assert module.nb_float(int, I(10)) == 10.0
876 assert module.nb_float(float, F(10.5)) == 10.5
877 # XXX but the subtype's tp_as_number->nb_float(x) should really invoke
878 # the user-defined __float__(); it doesn't so far
879 #assert module.nb_float(I, I(10)) == -55.55
880 #assert module.nb_float(F, F(10.5)) == -66.66
881
882 def test_tp_call(self):
883 module = self.import_extension('foo', [
884 ("tp_call", "METH_VARARGS",
885 '''
886 PyTypeObject *type = (PyTypeObject *)PyTuple_GET_ITEM(args, 0);
887 PyObject *obj = PyTuple_GET_ITEM(args, 1);
888 PyObject *c_args = PyTuple_GET_ITEM(args, 2);
889 if (!type->tp_call)
890 {
891 PyErr_SetNone(PyExc_ValueError);
892 return NULL;
893 }
894 return type->tp_call(obj, c_args, NULL);
895 '''
896 )
897 ])
898 class C:
899 def __call__(self, *args):
900 return args
901 ret = module.tp_call(C, C(), ('x', 2))
902 assert ret == ('x', 2)
903 class D(type):
904 def __call__(self, *args):
905 return "foo! %r" % (args,)
906 typ1 = D('d', (), {})
907 #assert module.tp_call(D, typ1, ()) == "foo! ()" XXX not working so far
908 assert isinstance(module.tp_call(type, typ1, ()), typ1)
909
910 def test_tp_init(self):
911 module = self.import_extension('foo', [
912 ("tp_init", "METH_VARARGS",
913 '''
914 PyTypeObject *type = (PyTypeObject *)PyTuple_GET_ITEM(args, 0);
915 PyObject *obj = PyTuple_GET_ITEM(args, 1);
916 PyObject *c_args = PyTuple_GET_ITEM(args, 2);
917 if (!type->tp_init)
918 {
919 PyErr_SetNone(PyExc_ValueError);
920 return NULL;
921 }
922 if (type->tp_init(obj, c_args, NULL) < 0)
923 return NULL;
924 Py_INCREF(Py_None);
925 return Py_None;
926 '''
927 )
928 ])
929 x = [42]
930 assert module.tp_init(list, x, ("hi",)) is None
931 assert x == ["h", "i"]
932 class LL(list):
933 def __init__(self, *ignored):
934 raise Exception
935 x = LL.__new__(LL)
936 assert module.tp_init(list, x, ("hi",)) is None
937 assert x == ["h", "i"]
938
939 init_called = []
940 class CALL(object):
941 def __init__(self):
942 init_called.append(42)
943 x = object.__new__(CALL)
944 x.__init__()
945 module.tp_init(CALL, x, ())
946 assert len(init_called) == 2, '%s' % len(init_called)
947
948 def test_mp_subscript(self):
949 module = self.import_extension('foo', [
950 ("new_obj", "METH_NOARGS",
951 '''
952 PyObject *obj;
953 obj = PyObject_New(PyObject, &Foo_Type);
954 return obj;
955 '''
956 )], prologue='''
957 static PyObject*
958 mp_subscript(PyObject *self, PyObject *key)
959 {
960 return Py_BuildValue("i", 42);
961 }
962 PyMappingMethods tp_as_mapping;
963 static PyTypeObject Foo_Type = {
964 PyVarObject_HEAD_INIT(NULL, 0)
965 "foo.foo",
966 };
967 ''', more_init = '''
968 Foo_Type.tp_flags = Py_TPFLAGS_DEFAULT;
969 Foo_Type.tp_as_mapping = &tp_as_mapping;
970 tp_as_mapping.mp_subscript = (binaryfunc)mp_subscript;
971 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
972 ''')
973 obj = module.new_obj()
974 assert obj[100] == 42
975 raises(TypeError, "obj.__getitem__(100, 101)")
976 raises(TypeError, "obj.__getitem__(100, a=42)")
977
978 def test_mp_ass_subscript(self):
979 module = self.import_extension('foo', [
980 ("new_obj", "METH_NOARGS",
981 '''
982 PyObject *obj;
983 obj = PyObject_New(PyObject, &Foo_Type);
984 return obj;
985 '''
986 )], prologue='''
987 static int
988 #if PY_MAJOR_VERSION > 2
989 #define PyString_FromString PyBytes_FromString
990 #define PyInt_Check PyLong_Check
991 #endif
992 mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
993 {
994 if (PyInt_Check(key)) {
995 PyErr_SetNone(PyExc_ZeroDivisionError);
996 return -1;
997 }
998 return 0;
999 }
1000 PyMappingMethods tp_as_mapping;
1001 static PyTypeObject Foo_Type = {
1002 PyVarObject_HEAD_INIT(NULL, 0)
1003 "foo.foo",
1004 };
1005 ''', more_init = '''
1006 Foo_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1007 Foo_Type.tp_as_mapping = &tp_as_mapping;
1008 tp_as_mapping.mp_ass_subscript = mp_ass_subscript;
1009 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
1010 ''')
1011 obj = module.new_obj()
1012 raises(ZeroDivisionError, obj.__setitem__, 5, None)
1013 res = obj.__setitem__('foo', None)
1014 assert res is None
1015
1016 def test_sq_contains(self):
1017 module = self.import_extension('foo', [
1018 ("new_obj", "METH_NOARGS",
1019 '''
1020 PyObject *obj;
1021 obj = PyObject_New(PyObject, &Foo_Type);
1022 return obj;
1023 '''
1024 )], prologue='''
1025 static int
1026 sq_contains(PyObject *self, PyObject *value)
1027 {
1028 return 42;
1029 }
1030 PySequenceMethods tp_as_sequence;
1031 static PyTypeObject Foo_Type = {
1032 PyVarObject_HEAD_INIT(NULL, 0)
1033 "foo.foo",
1034 };
1035 ''', more_init='''
1036 Foo_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1037 Foo_Type.tp_as_sequence = &tp_as_sequence;
1038 tp_as_sequence.sq_contains = sq_contains;
1039 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
1040 ''')
1041 obj = module.new_obj()
1042 res = "foo" in obj
1043 assert res is True
1044
1045 #if PY_MAJOR_VERSION > 2
1046 #define PyInt_Check PyLong_Check
1047 #define PyInt_AsLong PyLong_AsLong
1048 #endif
1049 def test_sq_ass_item(self):
1050 module = self.import_extension('foo', [
1051 ("new_obj", "METH_NOARGS",
1052 '''
1053 PyObject *obj;
1054 obj = PyObject_New(PyObject, &Foo_Type);
1055 return obj;
1056 '''
1057 )], prologue='''
1058 #if PY_MAJOR_VERSION > 2
1059 #define PyInt_Check PyLong_Check
1060 #define PyInt_AsLong PyLong_AsLong
1061 #endif
1062 static int
1063 sq_ass_item(PyObject *self, Py_ssize_t i, PyObject *o)
1064 {
1065 int expected;
1066 if (o == NULL) // delitem
1067 expected = (i == 12);
1068 else // setitem
1069 expected = (i == 10 && PyInt_Check(o) && PyInt_AsLong(o) == 42);
1070 if (!expected) {
1071 PyErr_SetString(PyExc_ValueError, "test failed");
1072 return -1;
1073 }
1074 return 0;
1075 }
1076 PySequenceMethods tp_as_sequence;
1077 static PyTypeObject Foo_Type = {
1078 PyVarObject_HEAD_INIT(NULL, 0)
1079 "foo.foo",
1080 };
1081 ''', more_init='''
1082 Foo_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1083 Foo_Type.tp_as_sequence = &tp_as_sequence;
1084 tp_as_sequence.sq_ass_item = sq_ass_item;
1085 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
1086 ''')
1087 obj = module.new_obj()
1088 obj[10] = 42
1089 raises(ValueError, "obj[10] = 43")
1090 raises(ValueError, "obj[11] = 42")
1091 del obj[12]
1092 raises(ValueError, "del obj[13]")
1093
1094 def test_tp_iter(self):
1095 module = self.import_extension('foo', [
1096 ("tp_iter", "METH_VARARGS",
1097 '''
1098 PyTypeObject *type = (PyTypeObject *)PyTuple_GET_ITEM(args, 0);
1099 PyObject *obj = PyTuple_GET_ITEM(args, 1);
1100 if (!type->tp_iter)
1101 {
1102 PyErr_SetNone(PyExc_ValueError);
1103 return NULL;
1104 }
1105 return type->tp_iter(obj);
1106 '''
1107 ),
1108 ("tp_iternext", "METH_VARARGS",
1109 '''
1110 #if PY_MAJOR_VERSION > 2
1111 #define PyString_FromString PyBytes_FromString
1112 #endif
1113 PyTypeObject *type = (PyTypeObject *)PyTuple_GET_ITEM(args, 0);
1114 PyObject *obj = PyTuple_GET_ITEM(args, 1);
1115 PyObject *result;
1116 if (!type->tp_iternext)
1117 {
1118 PyErr_SetNone(PyExc_ValueError);
1119 return NULL;
1120 }
1121 result = type->tp_iternext(obj);
1122 /* In py3, returning NULL from tp_iternext means the iterator
1123 * is exhausted */
1124 if (!result && !PyErr_Occurred())
1125 result = PyString_FromString("stop!");
1126 return result;
1127 '''
1128 )
1129 ])
1130 l = [1]
1131 it = module.tp_iter(list, l)
1132 assert type(it) is type(iter([]))
1133 assert module.tp_iternext(type(it), it) == 1
1134 assert module.tp_iternext(type(it), it) == b"stop!"
1135 #
1136 class LL(list):
1137 def __iter__(self):
1138 return iter(())
1139 ll = LL([1])
1140 it = module.tp_iter(list, ll)
1141 assert type(it) is type(iter([]))
1142 x = list(it)
1143 assert x == [1]
1144
1145 def test_gen_tp_iter(self):
1146 """
1147 module = self.import_extension('foo', [
1148 ("gen_tp_iternext", "METH_VARARGS",
1149 '''
1150 PyObject *obj = PyTuple_GET_ITEM(args, 0);
1151 iternextfunc next = Py_TYPE(obj)->tp_iternext;
1152 PyObject *result = next(obj);
1153 /* In py3, returning NULL from tp_iternext means the iterator
1154 * is exhausted, and the result is given in a StopIteration object */
1155 if (!result) {
1156 if (!PyErr_Occurred()) {
1157 PyErr_SetString(PyExc_AssertionError, "No StopIteration with NULL return value");
1158 return NULL;
1159 }
1160
1161 PyObject *ptype, *pvalue, *ptraceback;
1162 PyErr_Fetch(&ptype, &pvalue, &ptraceback);
1163 if (PyErr_GivenExceptionMatches(pvalue, PyExc_StopIteration)) {
1164 result = PyObject_GetAttrString(pvalue, "value");
1165 Py_XDECREF(pvalue);
1166 }
1167 else {
1168 result = pvalue;
1169 }
1170 Py_XDECREF(ptype);
1171 Py_XDECREF(ptraceback);
1172 }
1173 return result;
1174 '''
1175 )
1176 ])
1177
1178 def generator():
1179 yield 1
1180 return 3
1181
1182 gen = generator()
1183 assert module.gen_tp_iternext(gen) == 1
1184 assert module.gen_tp_iternext(gen) == 3
1185 """
1186
1187 def test_intlike(self):
1188 module = self.import_extension('foo', [
1189 ("newInt", "METH_VARARGS",
1190 """
1191 IntLikeObject *intObj;
1192 long intval;
1193
1194 if (!PyArg_ParseTuple(args, "i", &intval))
1195 return NULL;
1196
1197 intObj = PyObject_New(IntLikeObject, &IntLike_Type);
1198 if (!intObj) {
1199 return NULL;
1200 }
1201
1202 intObj->value = intval;
1203 return (PyObject *)intObj;
1204 """),
1205 ("check", "METH_VARARGS", """
1206 IntLikeObject *intObj;
1207 int intval, isint;
1208
1209 if (!PyArg_ParseTuple(args, "i", &intval))
1210 return NULL;
1211 intObj = PyObject_New(IntLikeObject, &IntLike_Type);
1212 if (!intObj) {
1213 return NULL;
1214 }
1215 intObj->value = intval;
1216 isint = PyNumber_Check((PyObject*)intObj);
1217 Py_DECREF((PyObject*)intObj);
1218 return PyLong_FromLong(isint);
1219 """),
1220 ], prologue= """
1221 typedef struct
1222 {
1223 PyObject_HEAD
1224 int value;
1225 } IntLikeObject;
1226
1227 static int
1228 intlike_nb_bool(PyObject *o)
1229 {
1230 IntLikeObject *v = (IntLikeObject*)o;
1231 if (v->value == -42) {
1232 PyErr_SetNone(PyExc_ValueError);
1233 return -1;
1234 }
1235 /* Returning -1 should be for exceptions only! */
1236 return v->value;
1237 }
1238
1239 static PyObject*
1240 intlike_nb_int(PyObject* o)
1241 {
1242 IntLikeObject *v = (IntLikeObject*)o;
1243 return PyLong_FromLong(v->value);
1244 }
1245
1246 PyTypeObject IntLike_Type = {
1247 PyVarObject_HEAD_INIT(NULL, 0)
1248 /*tp_name*/ "IntLike",
1249 /*tp_basicsize*/ sizeof(IntLikeObject),
1250 };
1251 static PyNumberMethods intlike_as_number;
1252 """, more_init="""
1253 IntLike_Type.tp_flags |= Py_TPFLAGS_DEFAULT;
1254 IntLike_Type.tp_as_number = &intlike_as_number;
1255 intlike_as_number.nb_bool = intlike_nb_bool;
1256 intlike_as_number.nb_int = intlike_nb_int;
1257 PyType_Ready(&IntLike_Type);
1258 """)
1259 assert not bool(module.newInt(0))
1260 assert bool(module.newInt(1))
1261 raises(SystemError, bool, module.newInt(-1))
1262 raises(ValueError, bool, module.newInt(-42))
1263 val = module.check(10);
1264 assert val == 1
1265
1266 def test_mathfunc(self):
1267 module = self.import_extension('foo', [
1268 ("newInt", "METH_VARARGS",
1269 """
1270 IntLikeObject *intObj;
1271 long intval;
1272
1273 if (!PyArg_ParseTuple(args, "l", &intval))
1274 return NULL;
1275
1276 intObj = PyObject_New(IntLikeObject, &IntLike_Type);
1277 if (!intObj) {
1278 return NULL;
1279 }
1280
1281 intObj->ival = intval;
1282 return (PyObject *)intObj;
1283 """),
1284 ("newIntNoOp", "METH_VARARGS",
1285 """
1286 IntLikeObjectNoOp *intObjNoOp;
1287 long intval;
1288
1289 if (!PyArg_ParseTuple(args, "l", &intval))
1290 return NULL;
1291
1292 intObjNoOp = PyObject_New(IntLikeObjectNoOp, &IntLike_Type_NoOp);
1293 if (!intObjNoOp) {
1294 return NULL;
1295 }
1296
1297 intObjNoOp->ival = intval;
1298 return (PyObject *)intObjNoOp;
1299 """)], prologue="""
1300 #include <math.h>
1301 typedef struct
1302 {
1303 PyObject_HEAD
1304 long ival;
1305 } IntLikeObject;
1306 #if PY_MAJOR_VERSION > 2
1307 #define PyInt_Check PyLong_Check
1308 #define PyInt_AsLong PyLong_AsLong
1309 #define PyInt_FromLong PyLong_FromLong
1310 #endif
1311 static PyObject *
1312 intlike_nb_add(PyObject *self, PyObject *other)
1313 {
1314 long val2, val1 = ((IntLikeObject *)(self))->ival;
1315 if (PyInt_Check(other)) {
1316 long val2 = PyInt_AsLong(other);
1317 return PyInt_FromLong(val1+val2);
1318 }
1319
1320 val2 = ((IntLikeObject *)(other))->ival;
1321 return PyInt_FromLong(val1+val2);
1322 }
1323
1324 static PyObject *
1325 intlike_nb_pow(PyObject *self, PyObject *other, PyObject * z)
1326 {
1327 long val2, val1 = ((IntLikeObject *)(self))->ival;
1328 if (PyInt_Check(other)) {
1329 long val2 = PyInt_AsLong(other);
1330 return PyInt_FromLong(val1+val2);
1331 }
1332
1333 val2 = ((IntLikeObject *)(other))->ival;
1334 return PyInt_FromLong((int)pow(val1,val2));
1335 }
1336
1337 PyTypeObject IntLike_Type = {
1338 PyVarObject_HEAD_INIT(NULL, 0)
1339 /*tp_name*/ "IntLike",
1340 /*tp_basicsize*/ sizeof(IntLikeObject),
1341 };
1342 static PyNumberMethods intlike_as_number;
1343
1344 typedef struct
1345 {
1346 PyObject_HEAD
1347 long ival;
1348 } IntLikeObjectNoOp;
1349
1350 PyTypeObject IntLike_Type_NoOp = {
1351 PyVarObject_HEAD_INIT(NULL, 0)
1352 /*tp_name*/ "IntLikeNoOp",
1353 /*tp_basicsize*/ sizeof(IntLikeObjectNoOp),
1354 };
1355 """, more_init="""
1356 IntLike_Type.tp_as_number = &intlike_as_number;
1357 IntLike_Type.tp_flags |= Py_TPFLAGS_DEFAULT;
1358 intlike_as_number.nb_add = intlike_nb_add;
1359 intlike_as_number.nb_power = intlike_nb_pow;
1360 if (PyType_Ready(&IntLike_Type) < 0) INITERROR;
1361 IntLike_Type_NoOp.tp_flags |= Py_TPFLAGS_DEFAULT;
1362 if (PyType_Ready(&IntLike_Type_NoOp) < 0) INITERROR;
1363 """)
1364 a = module.newInt(1)
1365 b = module.newInt(2)
1366 c = 3
1367 d = module.newIntNoOp(4)
1368 assert (a + b) == 3
1369 assert (b + c) == 5
1370 assert (d + a) == 5
1371 assert pow(d,b) == 16
1372
1373 def test_app_subclass_of_c_type(self):
1374 import sys
1375 module = self.import_module(name='foo')
1376 size = module.size_of_instances(module.fooType)
1377 class f1(object):
1378 pass
1379 class f2(module.fooType):
1380 pass
1381 class bar(f1, f2):
1382 pass
1383 class foo(f2, f1):
1384 pass
1385
1386 x = foo()
1387 assert bar.__base__ is f2
1388 # On cpython, the size changes.
1389 if '__pypy__' in sys.builtin_module_names:
1390 assert module.size_of_instances(bar) == size
1391 else:
1392 assert module.size_of_instances(bar) >= size
1393 assert module.size_of_instances(foo) == module.size_of_instances(bar)
1394
1395 def test_app_cant_subclass_two_types(self):
1396 import sys
1397 if sys.version_info < (2, 7, 9):
1398 skip("crashes on CPython (2.7.5 crashes, 2.7.9 is ok)")
1399 module = self.import_module(name='foo')
1400 try:
1401 class bar(module.fooType, module.UnicodeSubtype):
1402 pass
1403 except TypeError as e:
1404 import sys
1405 if '__pypy__' in sys.builtin_module_names:
1406 assert 'instance layout conflicts in multiple inheritance' in str(e)
1407
1408 else:
1409 assert 'instance lay-out conflict' in str(e)
1410 else:
1411 raise AssertionError("did not get TypeError!")
1412
1413 def test_call_tp_dealloc(self):
1414 module = self.import_extension('foo', [
1415 ("fetchFooType", "METH_NOARGS",
1416 """
1417 PyObject *o;
1418 o = PyObject_New(PyObject, &Foo_Type);
1419 init_foo(o);
1420 Py_DECREF(o); /* calls dealloc_foo immediately */
1421
1422 Py_INCREF(&Foo_Type);
1423 return (PyObject *)&Foo_Type;
1424 """),
1425 ("newInstance", "METH_O",
1426 """
1427 PyTypeObject *tp = (PyTypeObject *)args;
1428 PyObject *e = PyTuple_New(0);
1429 PyObject *o = tp->tp_new(tp, e, NULL);
1430 Py_DECREF(e);
1431 return o;
1432 """),
1433 ("getCounter", "METH_NOARGS",
1434 """
1435 return PyLong_FromLong(foo_counter);
1436 """)], prologue="""
1437 typedef struct {
1438 PyObject_HEAD
1439 int someval[99];
1440 } FooObject;
1441 static int foo_counter = 1000;
1442 static void dealloc_foo(PyObject *foo) {
1443 int i;
1444 foo_counter += 10;
1445 for (i = 0; i < 99; i++)
1446 if (((FooObject *)foo)->someval[i] != 1000 + i)
1447 foo_counter += 100000; /* error! */
1448 Py_TYPE(foo)->tp_free(foo);
1449 }
1450 static void init_foo(PyObject *o)
1451 {
1452 int i;
1453 if (o->ob_type->tp_basicsize < sizeof(FooObject))
1454 abort();
1455 for (i = 0; i < 99; i++)
1456 ((FooObject *)o)->someval[i] = 1000 + i;
1457 }
1458 static PyObject *new_foo(PyTypeObject *t, PyObject *a, PyObject *k)
1459 {
1460 PyObject *o;
1461 foo_counter += 1000;
1462 o = t->tp_alloc(t, 0);
1463 init_foo(o);
1464 return o;
1465 }
1466 static PyTypeObject Foo_Type = {
1467 PyVarObject_HEAD_INIT(NULL, 0)
1468 "foo.foo",
1469 };
1470 """, more_init="""
1471 Foo_Type.tp_basicsize = sizeof(FooObject);
1472 Foo_Type.tp_dealloc = &dealloc_foo;
1473 Foo_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
1474 Foo_Type.tp_new = &new_foo;
1475 Foo_Type.tp_free = &PyObject_Del;
1476 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
1477 """)
1478 Foo = module.fetchFooType()
1479 assert module.getCounter() == 1010
1480 Foo(); Foo()
1481 for i in range(10):
1482 if module.getCounter() >= 3030:
1483 break
1484 # NB. use self.debug_collect() instead of gc.collect(),
1485 # otherwise rawrefcount's dealloc callback doesn't trigger
1486 self.debug_collect()
1487 assert module.getCounter() == 3030
1488 #
1489 class Bar(Foo):
1490 pass
1491 assert Foo.__new__ is Bar.__new__
1492 Bar(); Bar()
1493 for i in range(10):
1494 if module.getCounter() >= 5050:
1495 break
1496 self.debug_collect()
1497 assert module.getCounter() == 5050
1498 #
1499 module.newInstance(Foo)
1500 for i in range(10):
1501 if module.getCounter() >= 6060:
1502 break
1503 self.debug_collect()
1504 assert module.getCounter() == 6060
1505 #
1506 module.newInstance(Bar)
1507 for i in range(10):
1508 if module.getCounter() >= 7070:
1509 break
1510 self.debug_collect()
1511 assert module.getCounter() == 7070
1512
1513 def test_tp_call_reverse(self):
1514 module = self.import_extension('foo', [
1515 ("new_obj", "METH_NOARGS",
1516 '''
1517 PyObject *obj;
1518 obj = PyObject_New(PyObject, &Foo_Type);
1519 return obj;
1520 '''
1521 )], prologue='''
1522 static PyObject *
1523 my_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
1524 {
1525 return PyLong_FromLong(42);
1526 }
1527 static PyTypeObject Foo_Type = {
1528 PyVarObject_HEAD_INIT(NULL, 0)
1529 "foo.foo",
1530 };
1531 ''', more_init='''
1532 Foo_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1533 Foo_Type.tp_call = &my_tp_call;
1534 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
1535 ''')
1536 x = module.new_obj()
1537 assert x() == 42
1538 assert x(4, bar=5) == 42
1539
1540 def test_custom_metaclass(self):
1541 module = self.import_extension('foo', [
1542 ("getMetaClass", "METH_NOARGS",
1543 '''
1544 Py_INCREF(&FooType_Type);
1545 return (PyObject *)&FooType_Type;
1546 '''
1547 )], prologue='''
1548 static PyTypeObject FooType_Type = {
1549 PyVarObject_HEAD_INIT(NULL, 0)
1550 "foo.Type",
1551 };
1552 ''', more_init='''
1553 FooType_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1554 FooType_Type.tp_base = &PyType_Type;
1555 if (PyType_Ready(&FooType_Type) < 0) INITERROR;
1556 ''')
1557 FooType = module.getMetaClass()
1558 if not self.runappdirect:
1559 self._check_type_object(FooType)
1560
1561 # 2 vs 3 shenanigans to declare
1562 # class X(object, metaclass=FooType): pass
1563 X = FooType('X', (object,), {})
1564
1565 X()
1566
1567 def test_multiple_inheritance3(self):
1568 module = self.import_extension('foo', [
1569 ("new_obj", "METH_NOARGS",
1570 '''
1571 PyObject *obj;
1572 PyTypeObject *Base1, *Base2, *Base12;
1573 Base1 = (PyTypeObject*)PyType_Type.tp_alloc(&PyType_Type, 0);
1574 Base2 = (PyTypeObject*)PyType_Type.tp_alloc(&PyType_Type, 0);
1575 Base12 = (PyTypeObject*)PyType_Type.tp_alloc(&PyType_Type, 0);
1576 Base1->tp_name = "Base1";
1577 Base2->tp_name = "Base2";
1578 Base12->tp_name = "Base12";
1579 Base1->tp_basicsize = sizeof(PyHeapTypeObject);
1580 Base2->tp_basicsize = sizeof(PyHeapTypeObject);
1581 Base12->tp_basicsize = sizeof(PyHeapTypeObject);
1582 PyObject * dummyname = PyUnicode_FromString("dummy name");
1583 ((PyHeapTypeObject*)Base1)->ht_qualname = dummyname;
1584 ((PyHeapTypeObject*)Base2)->ht_qualname = dummyname;
1585 ((PyHeapTypeObject*)Base12)->ht_qualname = dummyname;
1586 ((PyHeapTypeObject*)Base1)->ht_name = PyUnicode_FromString("Base1");
1587 ((PyHeapTypeObject*)Base2)->ht_name = PyUnicode_FromString("Base2");
1588 ((PyHeapTypeObject*)Base12)->ht_name = PyUnicode_FromString("Base12");
1589 Base1->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
1590 Base2->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
1591 Base12->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
1592 Base12->tp_base = Base1;
1593 Base12->tp_bases = PyTuple_Pack(2, Base1, Base2);
1594 Base12->tp_doc = "The Base12 type or object";
1595 if (PyType_Ready(Base1) < 0) return NULL;
1596 if (PyType_Ready(Base2) < 0) return NULL;
1597 if (PyType_Ready(Base12) < 0) return NULL;
1598 obj = PyObject_New(PyObject, Base12);
1599 return obj;
1600 '''
1601 ),
1602 ("test_getslot", "METH_O",
1603 '''
1604 PyTypeObject *typ = (PyTypeObject *)PyObject_Type(args);
1605 if (! PyType_HasFeature(typ, Py_TPFLAGS_HEAPTYPE) ) {
1606 return PyLong_FromLong(-1);
1607 }
1608 void * tp_bases = PyType_GetSlot(typ, Py_tp_bases);
1609 long eq = (tp_bases == (void*)typ->tp_bases);
1610 return PyLong_FromLong(eq);
1611 '''),
1612 ("test_tp_new", "METH_NOARGS",
1613 '''
1614 newfunc tp_new = PyType_GetSlot(&PyLong_Type, Py_tp_new);
1615 if (PyLong_Type.tp_new != tp_new) {
1616 PyErr_SetString(PyExc_AssertionError, "mismatch: tp_new of long");
1617 return NULL;
1618 }
1619 Py_RETURN_NONE;
1620 '''),
1621 ("test_nb_add", "METH_NOARGS",
1622 '''
1623 binaryfunc nb_add = PyType_GetSlot(&PyLong_Type, Py_nb_add);
1624 if (PyLong_Type.tp_as_number->nb_add != nb_add) {
1625 PyErr_SetString(PyExc_AssertionError, "mismatch: nb_add of long");
1626 return NULL;
1627 }
1628 Py_RETURN_NONE;
1629 '''),
1630 ("test_zero", "METH_NOARGS",
1631 '''
1632 binaryfunc nb_add = PyType_GetSlot(&PyLong_Type, 0);
1633 if (nb_add != NULL) {
1634 PyErr_SetString(PyExc_AssertionError,
1635 "PyType_GetSlot should not succeed");
1636 }
1637 return NULL;
1638 '''),
1639 ])
1640 obj = module.new_obj()
1641 assert 'Base12' in str(obj)
1642 assert type(obj).__doc__ == "The Base12 type or object"
1643 assert obj.__doc__ == "The Base12 type or object"
1644 assert module.test_getslot(obj) == 1
1645 module.test_tp_new()
1646 module.test_nb_add()
1647 with raises(SystemError):
1648 module.test_zero()
1649
1650 def test_multiple_inheritance_small_basicsize(self):
1651 # Regression test: two manually-allocated heap types whose tp_basicsize
1652 # is smaller than sizeof(PyHeapTypeObject) (as pybind11 does) must be
1653 # combinable in multiple inheritance when they share the same
1654 # tp_basicsize, because there is no actual instance-layout conflict.
1655 module = self.import_extension('foo', [
1656 ("new_obj", "METH_NOARGS",
1657 '''
1658 /* Simulate pybind11: instance struct is PyObject_HEAD + one ptr,
1659 which is << sizeof(PyHeapTypeObject). */
1660 typedef struct { PyObject_HEAD; void *extra; } SmallInst;
1661 Py_ssize_t inst_size = (Py_ssize_t)sizeof(SmallInst);
1662
1663 PyTypeObject *B1, *B2, *B12;
1664 B1 = (PyTypeObject*)PyType_Type.tp_alloc(&PyType_Type, 0);
1665 B2 = (PyTypeObject*)PyType_Type.tp_alloc(&PyType_Type, 0);
1666 B12 = (PyTypeObject*)PyType_Type.tp_alloc(&PyType_Type, 0);
1667
1668 PyObject *n1 = PyUnicode_FromString("B1");
1669 PyObject *n2 = PyUnicode_FromString("B2");
1670 PyObject *n12 = PyUnicode_FromString("B12");
1671
1672 B1->tp_name = "B1";
1673 B2->tp_name = "B2";
1674 B12->tp_name = "B12";
1675
1676 B1->tp_basicsize = inst_size;
1677 B2->tp_basicsize = inst_size;
1678 B12->tp_basicsize = inst_size;
1679
1680 ((PyHeapTypeObject*)B1)->ht_name = n1;
1681 ((PyHeapTypeObject*)B2)->ht_name = n2;
1682 ((PyHeapTypeObject*)B12)->ht_name = n12;
1683 ((PyHeapTypeObject*)B1)->ht_qualname = n1;
1684 ((PyHeapTypeObject*)B2)->ht_qualname = n2;
1685 ((PyHeapTypeObject*)B12)->ht_qualname = n12;
1686
1687 B1->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
1688 B2->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
1689 B12->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
1690
1691 B12->tp_base = B1;
1692 B12->tp_bases = PyTuple_Pack(2, B1, B2);
1693
1694 if (PyType_Ready(B1) < 0) return NULL;
1695 if (PyType_Ready(B2) < 0) return NULL;
1696 if (PyType_Ready(B12) < 0) return NULL;
1697
1698 PyObject *obj = PyObject_New(PyObject, B12);
1699 return obj;
1700 '''
1701 ),
1702 ])
1703 obj = module.new_obj()
1704 assert 'B12' in str(obj)
1705
1706 def test_multiple_inheritance_python_subclass_of_two_cpytypes(self):
1707 # Regression test: Python code must be able to create a class that
1708 # inherits from two cpytype bases that share the same solid base
1709 # (i.e. have equivalent layouts), as pybind11 does with Base1/Base2.
1710 # The previous fix (issue 5481) only covered the case where the new
1711 # type itself was a cpytype (created via PyType_Ready); this covers
1712 # the Python-level "class MI1(B1, B2):" case.
1713 module = self.import_extension('foo', [
1714 ("get_bases", "METH_NOARGS",
1715 '''
1716 /* Simulate two independent pybind11-style types: both have the
1717 same tp_basicsize (larger than PyObject but smaller than
1718 PyHeapTypeObject), both inherit from the same base. */
1719 typedef struct { PyObject_HEAD; void *holder; } PybindInst;
1720 Py_ssize_t inst_size = (Py_ssize_t)sizeof(PybindInst);
1721
1722 /* Shared object base (analogous to pybind11_object). */
1723 PyTypeObject *ObjBase;
1724 ObjBase = (PyTypeObject*)PyType_Type.tp_alloc(&PyType_Type, 0);
1725 PyObject *nobj = PyUnicode_FromString("ObjBase");
1726 ObjBase->tp_name = "ObjBase";
1727 ObjBase->tp_basicsize = inst_size;
1728 ((PyHeapTypeObject*)ObjBase)->ht_name = nobj;
1729 ((PyHeapTypeObject*)ObjBase)->ht_qualname = nobj;
1730 ObjBase->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
1731 if (PyType_Ready(ObjBase) < 0) return NULL;
1732
1733 PyTypeObject *B1, *B2;
1734 B1 = (PyTypeObject*)PyType_Type.tp_alloc(&PyType_Type, 0);
1735 B2 = (PyTypeObject*)PyType_Type.tp_alloc(&PyType_Type, 0);
1736
1737 PyObject *n1 = PyUnicode_FromString("B1");
1738 PyObject *n2 = PyUnicode_FromString("B2");
1739 B1->tp_name = "B1";
1740 B2->tp_name = "B2";
1741 B1->tp_basicsize = inst_size;
1742 B2->tp_basicsize = inst_size;
1743 ((PyHeapTypeObject*)B1)->ht_name = n1;
1744 ((PyHeapTypeObject*)B2)->ht_name = n2;
1745 ((PyHeapTypeObject*)B1)->ht_qualname = n1;
1746 ((PyHeapTypeObject*)B2)->ht_qualname = n2;
1747 B1->tp_base = ObjBase; Py_INCREF(ObjBase);
1748 B2->tp_base = ObjBase; Py_INCREF(ObjBase);
1749 B1->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
1750 B2->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
1751 if (PyType_Ready(B1) < 0) return NULL;
1752 if (PyType_Ready(B2) < 0) return NULL;
1753
1754 return PyTuple_Pack(2, B1, B2);
1755 '''
1756 ),
1757 ])
1758 B1, B2 = module.get_bases()
1759 # This must not raise "instance layout conflicts in multiple inheritance"
1760 class MI1(B1, B2):
1761 pass
1762 obj = MI1()
1763 assert isinstance(obj, B1)
1764 assert isinstance(obj, B2)
1765
1766 def test_multiple_inheritance_fetch_tp_bases(self):
1767 module = self.import_extension('foo', [
1768 ("foo", "METH_O",
1769 '''
1770 PyTypeObject *tp;
1771 tp = (PyTypeObject*)args;
1772 Py_INCREF(tp->tp_bases);
1773 return tp->tp_bases;
1774 '''
1775 )])
1776 class A(object):
1777 pass
1778 class B(object):
1779 pass
1780 class C(A, B):
1781 pass
1782 bases = module.foo(C)
1783 assert bases == (A, B)
1784
1785 def test_getattr_getattro(self):
1786 module = self.import_module(name='foo')
1787 assert module.gettype2.dcba == b'getattro:dcba'
1788 assert (type(module.gettype2).__getattribute__(module.gettype2, 'dcBA')
1789 == b'getattro:dcBA')
1790 assert module.gettype1.abcd == b'getattr:abcd'
1791 # GetType1 objects have a __getattribute__ method, but this
1792 # doesn't call tp_getattr at all, also on CPython
1793 raises(AttributeError, type(module.gettype1).__getattribute__,
1794 module.gettype1, 'dcBA')
1795
1796 def test_multiple_inheritance_tp_basicsize(self):
1797 module = self.import_module(name='issue2482')
1798
1799 class PyBase(object):
1800 pass
1801
1802 basesize = module.get_basicsize(PyBase)
1803
1804 CBase = module.issue2482_object
1805 class A(CBase, PyBase):
1806 def __init__(self, i):
1807 CBase.__init__(self)
1808 PyBase.__init__(self)
1809
1810 class B(PyBase, CBase):
1811 def __init__(self, i):
1812 PyBase.__init__(self)
1813 CBase.__init__(self)
1814
1815 Asize = module.get_basicsize(A)
1816 Bsize = module.get_basicsize(B)
1817 assert Asize == Bsize
1818 assert Asize > basesize
1819
1820 def test_multiple_inheritance_bug1(self):
1821 module = self.import_extension('foo', [
1822 ("get_type", "METH_NOARGS",
1823 '''
1824 Py_INCREF(&Foo_Type);
1825 return (PyObject *)&Foo_Type;
1826 '''
1827 ), ("forty_two", "METH_O",
1828 '''
1829 return PyInt_FromLong(42);
1830 '''
1831 )], prologue='''
1832 #if PY_MAJOR_VERSION > 2
1833 #define PyInt_FromLong PyLong_FromLong
1834 #endif
1835 static PyTypeObject Foo_Type = {
1836 PyVarObject_HEAD_INIT(NULL, 0)
1837 "foo.foo",
1838 };
1839 static PyObject *dummy_new(PyTypeObject *t, PyObject *a,
1840 PyObject *k)
1841 {
1842 abort(); /* never actually called in CPython */
1843 }
1844 ''', more_init = '''
1845 Foo_Type.tp_base = (PyTypeObject *)PyExc_Exception;
1846 Foo_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;
1847 Foo_Type.tp_new = dummy_new;
1848 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
1849 ''')
1850 Foo = module.get_type()
1851 class A(Foo, SyntaxError):
1852 pass
1853 assert A.__base__ is SyntaxError
1854 A(42) # assert is not aborting
1855
1856 class Bar(Exception):
1857 __new__ = module.forty_two
1858
1859 class B(Bar, SyntaxError):
1860 pass
1861
1862 assert B() == 42
1863
1864 # aaaaa even more hackiness
1865 class C(A):
1866 pass
1867 C(42) # assert is not aborting
1868
1869 def test_getset(self):
1870 module = self.import_extension('foo', [
1871 ("get_instance", "METH_NOARGS",
1872 '''
1873 return PyObject_New(PyObject, &Foo_Type);
1874 '''
1875 ), ("get_number", "METH_NOARGS",
1876 '''
1877 return PyInt_FromLong(my_global_number);
1878 '''
1879 )], prologue='''
1880 #if PY_MAJOR_VERSION > 2
1881 #define PyInt_FromLong PyLong_FromLong
1882 #define PyInt_AsLong PyLong_AsLong
1883 #endif
1884 static long my_global_number;
1885 static PyTypeObject Foo_Type = {
1886 PyVarObject_HEAD_INIT(NULL, 0)
1887 "foo.foo",
1888 };
1889 static PyObject *bar_get(PyObject *foo, void *closure)
1890 {
1891 return PyInt_FromLong(1000 + (long)closure);
1892 }
1893 static PyObject *baz_get(PyObject *foo, void *closure)
1894 {
1895 return PyInt_FromLong(2000 + (long)closure);
1896 }
1897 static int baz_set(PyObject *foo, PyObject *x, void *closure)
1898 {
1899 if (x != NULL)
1900 my_global_number = 3000 + (long)closure + PyInt_AsLong(x);
1901 else
1902 my_global_number = 4000 + (long)closure;
1903 return 0;
1904 }
1905 static PyGetSetDef foo_getset[] = {
1906 { "bar", bar_get, NULL, "mybardoc", (void *)42 },
1907 { "baz", baz_get, baz_set, "mybazdoc", (void *)43 },
1908 { NULL }
1909 };
1910 ''', more_init = '''
1911 Foo_Type.tp_getset = foo_getset;
1912 Foo_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1913 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
1914 ''')
1915 foo = module.get_instance()
1916 assert foo.bar == 1042
1917 assert foo.bar == 1042
1918 assert foo.baz == 2043
1919 foo.baz = 50000
1920 assert module.get_number() == 53043
1921 e = raises(AttributeError, "foo.bar = 0")
1922 assert str(e.value).startswith("attribute 'bar' of '")
1923 assert str(e.value).endswith("foo' objects is not writable")
1924 del foo.baz
1925 assert module.get_number() == 4043
1926 raises(AttributeError, "del foo.bar")
1927
1928 def test_tp_doc_issue3055(self):
1929 module = self.import_extension('foo', [
1930 ("new_obj", "METH_NOARGS",
1931 '''
1932 PyObject *obj;
1933 obj = PyObject_New(PyObject, &Foo_Type);
1934 return obj;
1935 '''
1936 )], prologue='''
1937 static PyTypeObject Foo_Type = {
1938 PyVarObject_HEAD_INIT(NULL, 0)
1939 "foo.foo",
1940 sizeof(PyObject),
1941 };
1942 ''', more_init = '''
1943 Foo_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1944 Foo_Type.tp_doc = "";
1945 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
1946 ''')
1947 obj = module.new_obj()
1948 assert type(obj).__doc__ is None
1949
1950 def test_vectorcall(self):
1951 module = self.import_extension('foo', [
1952 ("pyobject_vectorcall", "METH_VARARGS",
1953 '''
1954 PyObject *func, *func_args, *kwnames = NULL;
1955 PyObject **stack;
1956 Py_ssize_t nargs;
1957
1958 if (!PyArg_ParseTuple(args, "OOO", &func, &func_args, &kwnames)) {
1959 return NULL;
1960 }
1961 if (args == Py_None) {
1962 stack = NULL;
1963 nargs = 0;
1964 }
1965 else if (PyTuple_Check(args)) {
1966 stack = ((PyTupleObject *)func_args)->ob_item;
1967 nargs = PyTuple_GET_SIZE(func_args);
1968 }
1969 if (kwnames == Py_None) {
1970 kwnames = NULL;
1971 }
1972 else if (PyTuple_Check(kwnames)) {
1973 Py_ssize_t nkw = PyTuple_GET_SIZE(kwnames);
1974 if (nargs < nkw) {
1975 PyErr_SetString(PyExc_ValueError, "kwnames longer than args");
1976 return NULL;
1977 }
1978 nargs -= nkw;
1979 }
1980 else {
1981 PyErr_SetString(PyExc_TypeError, "kwnames must be None or a tuple");
1982 return NULL;
1983 }
1984 return PyObject_Vectorcall(func, stack, nargs, kwnames);
1985 '''),
1986 ("pyvectorcall_call", "METH_VARARGS",
1987 # taken from _testcapimodule.c
1988 '''
1989 PyObject *func;
1990 PyObject *argstuple;
1991 PyObject *kwargs = NULL;
1992
1993 if (!PyArg_ParseTuple(args, "OO|O", &func, &argstuple, &kwargs)) {
1994 return NULL;
1995 }
1996
1997 if (!PyTuple_Check(argstuple)) {
1998 PyErr_SetString(PyExc_TypeError, "args must be a tuple");
1999 return NULL;
2000 }
2001 if (kwargs != NULL && !PyDict_Check(kwargs)) {
2002 PyErr_SetString(PyExc_TypeError, "kwargs must be a dict");
2003 return NULL;
2004 }
2005
2006 return PyVectorcall_Call(func, argstuple, kwargs);
2007 '''),
2008 ],
2009 prologue="""
2010 #include <stddef.h>
2011 typedef struct {
2012 PyObject_HEAD
2013 vectorcallfunc vectorcall;
2014 } MethodDescriptorObject;
2015
2016 static PyObject *
2017 MethodDescriptor_vectorcall(PyObject *callable, PyObject *const *args,
2018 size_t nargsf, PyObject *kwnames)
2019 {
2020 /* True if using the vectorcall function in MethodDescriptorObject
2021 * but False for MethodDescriptor2Object */
2022 MethodDescriptorObject *md = (MethodDescriptorObject *)callable;
2023 return PyBool_FromLong(md->vectorcall != NULL);
2024 }
2025
2026 static PyObject *
2027 MethodDescriptor_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2028 {
2029 MethodDescriptorObject *op = (MethodDescriptorObject *)type->tp_alloc(type, 0);
2030 op->vectorcall = MethodDescriptor_vectorcall;
2031 return (PyObject *)op;
2032 }
2033
2034 static PyObject *
2035 func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
2036 {
2037 if (obj == Py_None || obj == NULL) {
2038 Py_INCREF(func);
2039 return func;
2040 }
2041 return PyMethod_New(func, obj);
2042 }
2043
2044 static PyObject *
2045 nop_descr_get(PyObject *func, PyObject *obj, PyObject *type)
2046 {
2047 Py_INCREF(func);
2048 return func;
2049 }
2050
2051 static PyObject *
2052 call_return_args(PyObject *self, PyObject *args, PyObject *kwargs)
2053 {
2054 Py_INCREF(args);
2055 return args;
2056 }
2057
2058 static PyTypeObject MethodDescriptorBase_Type = {
2059 PyVarObject_HEAD_INIT(NULL, 0)
2060 "MethodDescriptorBase",
2061 sizeof(MethodDescriptorObject),
2062 .tp_new = MethodDescriptor_new,
2063 .tp_call = PyVectorcall_Call,
2064 .tp_vectorcall_offset = offsetof(MethodDescriptorObject, vectorcall),
2065 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
2066 Py_TPFLAGS_METHOD_DESCRIPTOR | Py_TPFLAGS_HAVE_VECTORCALL,
2067 .tp_descr_get = func_descr_get,
2068 };
2069
2070 static PyTypeObject MethodDescriptorDerived_Type = {
2071 PyVarObject_HEAD_INIT(NULL, 0)
2072 "MethodDescriptorDerived",
2073 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2074 };
2075
2076 typedef struct {
2077 MethodDescriptorObject base;
2078 vectorcallfunc vectorcall;
2079 } MethodDescriptor2Object;
2080
2081 static PyObject *
2082 MethodDescriptor2_new(PyTypeObject* type, PyObject* args, PyObject *kw)
2083 {
2084 MethodDescriptor2Object *op = PyObject_New(MethodDescriptor2Object, type);
2085 op->base.vectorcall = NULL;
2086 op->vectorcall = MethodDescriptor_vectorcall;
2087 return (PyObject *)op;
2088 }
2089
2090 static PyTypeObject MethodDescriptor2_Type = {
2091 PyVarObject_HEAD_INIT(NULL, 0)
2092 "MethodDescriptor2",
2093 sizeof(MethodDescriptor2Object),
2094 .tp_new = MethodDescriptor2_new,
2095 .tp_call = PyVectorcall_Call,
2096 .tp_vectorcall_offset = offsetof(MethodDescriptor2Object, vectorcall),
2097 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_VECTORCALL,
2098 };
2099
2100 static PyTypeObject MethodDescriptorNopGet_Type = {
2101 PyVarObject_HEAD_INIT(NULL, 0)
2102 "MethodDescriptorNopGet",
2103 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2104 .tp_call = call_return_args,
2105 .tp_descr_get = nop_descr_get,
2106 };
2107
2108 """,
2109 more_init="""
2110 if (PyType_Ready(&MethodDescriptorBase_Type) < 0)
2111 INITERROR;
2112 Py_INCREF(&MethodDescriptorBase_Type);
2113 PyModule_AddObject(mod, "MethodDescriptorBase",
2114 (PyObject *)&MethodDescriptorBase_Type);
2115 MethodDescriptorDerived_Type.tp_base = &MethodDescriptorBase_Type;
2116 if (PyType_Ready(&MethodDescriptorDerived_Type) < 0)
2117 INITERROR;
2118 Py_INCREF(&MethodDescriptorDerived_Type);
2119 PyModule_AddObject(mod, "MethodDescriptorDerived",
2120 (PyObject *)&MethodDescriptorDerived_Type);
2121
2122 MethodDescriptor2_Type.tp_base = &MethodDescriptorBase_Type;
2123 if (PyType_Ready(&MethodDescriptor2_Type) < 0)
2124 return NULL;
2125 Py_INCREF(&MethodDescriptor2_Type);
2126 PyModule_AddObject(mod, "MethodDescriptor2", (PyObject *)&MethodDescriptor2_Type);
2127
2128 MethodDescriptorNopGet_Type.tp_base = &MethodDescriptorBase_Type;
2129 if (PyType_Ready(&MethodDescriptorNopGet_Type) < 0)
2130 INITERROR;
2131 Py_INCREF(&MethodDescriptorNopGet_Type);
2132 PyModule_AddObject(mod, "MethodDescriptorNopGet",
2133 (PyObject *)&MethodDescriptorNopGet_Type);
2134 """)
2135 def pyfunc(arg1, arg2):
2136 return [arg1, arg2]
2137
2138 def testfunction(self):
2139 """some doc"""
2140 return self
2141
2142 def testfunction_kw(self, **kw):
2143 """some doc"""
2144 return self
2145
2146 res = module.pyobject_vectorcall(pyfunc, (1, 2), None)
2147 assert res == [1, 2]
2148 res = module.pyobject_vectorcall(pyfunc, (1, 2), ("arg2", ))
2149 assert res == [1, 2]
2150 method = module.MethodDescriptorBase()
2151 res = module.pyobject_vectorcall(method, (0, ), None)
2152 assert res == True
2153
2154 calls = [(len, (range(42),), {}, 42),
2155 (list.append, ([], 0), {}, None),
2156 ([].append, (0,), {}, None),
2157 (sum, ([36],), {"start":6}, 42),
2158 (testfunction, (42,), {}, 42),
2159 (testfunction_kw, (42,), {"kw":None}, 42),
2160 (module.MethodDescriptorBase(), (0,), {}, True),
2161 (module.MethodDescriptorDerived(), (0,), {}, True),
2162 (module.MethodDescriptor2(), (0,), {}, False)]
2163
2164 from types import MethodType
2165 from functools import partial
2166
2167 def vectorcall(func, *args, **kwargs):
2168 if kwargs:
2169 args = args + tuple(kwargs.values())
2170 kwnames = tuple(kwargs.keys())
2171 return module.pyobject_vectorcall(func, args, kwnames)
2172
2173 for (func, args, kwargs, expected) in calls:
2174 if not kwargs:
2175 assert expected == module.pyvectorcall_call(func, args)
2176 assert expected == module.pyvectorcall_call(func, args, kwargs)
2177
2178 # Add derived classes (which do not support vectorcall directly,
2179 # but do support all other ways of calling).
2180
2181 class MethodDescriptorHeap(module.MethodDescriptorBase):
2182 pass
2183
2184 class MethodDescriptorOverridden(module.MethodDescriptorBase):
2185 def __call__(self, n):
2186 return 'new'
2187
2188 class SuperBase:
2189 def __call__(self, *args):
2190 return super().__call__(*args)
2191
2192 class MethodDescriptorSuper(SuperBase, module.MethodDescriptorBase):
2193 def __call__(self, *args):
2194 return super().__call__(*args)
2195
2196 calls += [
2197 (dict.update, ({},), {"key":True}, None),
2198 ({}.update, ({},), {"key":True}, None),
2199 (MethodDescriptorHeap(), (0,), {}, True),
2200 (MethodDescriptorOverridden(), (0,), {}, 'new'),
2201 (MethodDescriptorSuper(), (0,), {}, True),
2202 ]
2203
2204 for (func, args, kwargs, expected) in calls:
2205 args1 = args[1:]
2206 meth = MethodType(func, args[0])
2207 wrapped = partial(func)
2208 if not kwargs:
2209 assert expected == func(*args)
2210 assert expected == module.pyobject_vectorcall(func, args, None)
2211 assert expected == meth(*args1)
2212 assert expected == wrapped(*args)
2213 assert expected == func(*args, **kwargs)
2214 assert expected == vectorcall(func, *args, **kwargs)
2215 assert expected == meth(*args1, **kwargs)
2216 assert expected == wrapped(*args, **kwargs)
2217
2218 Py_TPFLAGS_HAVE_VECTORCALL = 1 << 11
2219 assert module.MethodDescriptor2.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL
2220
2221 # test_vectorcall_flag: derived static type should inherit Py_TPFLAGS_HAVE_VECTORCALL
2222 assert module.MethodDescriptorBase.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL
2223 assert module.MethodDescriptorDerived.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL
2224 class MethodDescriptorHeap(module.MethodDescriptorBase):
2225 pass
2226 assert not (MethodDescriptorHeap.__flags__ & Py_TPFLAGS_HAVE_VECTORCALL)
2227
2228 # test_method_descriptor_flag: Py_TPFLAGS_METHOD_DESCRIPTOR on C extension types
2229 Py_TPFLAGS_METHOD_DESCRIPTOR = 1 << 17
2230 assert module.MethodDescriptorBase.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR
2231 assert module.MethodDescriptorDerived.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR
2232 assert not (MethodDescriptorHeap.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
2233 assert not (module.MethodDescriptorNopGet.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
2234
2235 def test_fastcall(self):
2236 module = self.import_extension('foo', [
2237 ("test_fastcall", "METH_VARARGS",
2238 '''
2239 PyObject *func, *func_args = NULL;
2240 PyObject **stack;
2241 Py_ssize_t nargs;
2242
2243 if (!PyArg_ParseTuple(args, "OO", &func, &func_args)) {
2244 return NULL;
2245 }
2246 if (args == Py_None) {
2247 stack = NULL;
2248 nargs = 0;
2249 }
2250 else if (PyTuple_Check(args)) {
2251 stack = ((PyTupleObject *)func_args)->ob_item;
2252 nargs = PyTuple_GET_SIZE(func_args);
2253 }
2254 return _PyObject_FastCall(func, stack, nargs);
2255 ''')])
2256 def pyfunc(arg1, arg2):
2257 return [arg1, arg2]
2258 res = module.test_fastcall(pyfunc, (1, 2))
2259 assert res == [1, 2]
2260
2261 def test_fastcalldict(self):
2262 module = self.import_extension('foo', [
2263 ("test_fastcalldict", "METH_VARARGS",
2264 '''
2265 PyObject *func, *func_args, *kwargs = NULL;
2266 PyObject **stack;
2267 Py_ssize_t nargs;
2268
2269 if (!PyArg_ParseTuple(args, "OOO", &func, &func_args, &kwargs)) {
2270 return NULL;
2271 }
2272 if (args == Py_None) {
2273 stack = NULL;
2274 nargs = 0;
2275 }
2276 else if (PyTuple_Check(args)) {
2277 stack = ((PyTupleObject *)func_args)->ob_item;
2278 nargs = PyTuple_GET_SIZE(func_args);
2279 }
2280 if (kwargs == Py_None) {
2281 kwargs = NULL;
2282 }
2283 else if (!PyDict_Check(kwargs)) {
2284 PyErr_SetString(PyExc_TypeError, "kwnames must be None or a dict");
2285 return NULL;
2286 }
2287 return PyObject_VectorcallDict(func, stack, nargs, kwargs);
2288 ''')])
2289 def pyfunc(arg1, arg2):
2290 return [arg1, arg2]
2291 res = module.test_fastcalldict(pyfunc, (1, 2), None)
2292 assert res == [1, 2]
2293 res = module.test_fastcalldict(pyfunc, (1, 2), {})
2294 assert res == [1, 2]
2295 res = module.test_fastcalldict(pyfunc, (1, ), {"arg2": 2})
2296 assert res == [1, 2]
2297
2298 def test_getset_doc(self):
2299 module = self.import_extension("foo", [
2300 ("getset_type", "METH_NOARGS",
2301 """
2302 PyObject *ret = PyType_FromSpec(&test_spec);
2303 return ret;
2304 """)], prologue="""
2305 typedef struct {
2306 PyObject_HEAD
2307 } Test;
2308
2309 static int test_init(PyObject *self, PyObject *args, PyObject *kwd) { return 0; }
2310 static PyObject *test_getter(PyObject *self, void* payload) { return PyLong_FromLong(123); }
2311
2312 static PyGetSetDef test_getset[] = {
2313 { "prop", test_getter, NULL, "A docstring", NULL },
2314 {NULL, NULL, NULL, NULL, NULL }
2315 };
2316
2317 static PyType_Slot test_slots[] = {
2318 { Py_tp_init, test_init },
2319 { Py_tp_getset, test_getset },
2320 { 0, NULL }
2321 };
2322
2323 static PyType_Spec test_spec = {
2324 .name = "Test",
2325 .flags = Py_TPFLAGS_DEFAULT,
2326 .slots = test_slots,
2327 .basicsize = (int) sizeof(Test),
2328 .itemsize = 0
2329 };
2330 """)
2331
2332 test = module.getset_type()
2333 assert test.prop.__doc__ == "A docstring"
2334
2335 def test_dictoffset(self):
2336 module = self.import_extension("foo", [
2337 ("negative_dictoffset", "METH_NOARGS",
2338 """
2339 return PyType_FromSpec(&HeapCTypeWithNegativeDict_spec);
2340 """),
2341
2342 ], prologue="""
2343 #include <structmember.h>
2344 typedef struct {
2345 PyObject_HEAD
2346 PyObject *dict;
2347 } HeapCTypeWithDictObject;
2348
2349 static void
2350 heapctypewithdict_dealloc(HeapCTypeWithDictObject* self)
2351 {
2352
2353 PyTypeObject *tp = Py_TYPE(self);
2354 Py_XDECREF(self->dict);
2355 PyObject_Free(self);
2356 Py_DECREF(tp);
2357 }
2358
2359 static PyGetSetDef heapctypewithdict_getsetlist[] = {
2360 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
2361 {NULL} /* Sentinel */
2362 };
2363
2364 static struct PyMemberDef heapctypewithnegativedict_members[] = {
2365 {"dictobj", T_OBJECT, offsetof(HeapCTypeWithDictObject, dict)},
2366 {"__dictoffset__", T_PYSSIZET, -(Py_ssize_t)sizeof(void*), READONLY},
2367 {NULL} /* Sentinel */
2368 };
2369
2370 static PyType_Slot HeapCTypeWithNegativeDict_slots[] = {
2371 {Py_tp_members, heapctypewithnegativedict_members},
2372 {Py_tp_getset, heapctypewithdict_getsetlist},
2373 {Py_tp_dealloc, heapctypewithdict_dealloc},
2374 {0, 0},
2375 };
2376
2377 static PyType_Spec HeapCTypeWithNegativeDict_spec = {
2378 "_testcapi.HeapCTypeWithNegativeDict",
2379 sizeof(HeapCTypeWithDictObject),
2380 0,
2381 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2382 HeapCTypeWithNegativeDict_slots
2383 };
2384 """)
2385 inst = module.negative_dictoffset()()
2386 inst.foo = 42
2387 assert inst.dictobj == inst.__dict__
2388 assert inst.dictobj == {"foo": 42}
2389
2390 def test_unhashable(self):
2391 if not self.runappdirect:
2392 skip('pointer to function equality available'
2393 ' only after translation')
2394 module = self.import_extension('foo', [
2395 ("new_obj", "METH_NOARGS",
2396 '''
2397 PyObject *obj;
2398 obj = PyObject_New(PyObject, &Foo_Type);
2399 return obj;
2400 '''
2401 )], prologue='''
2402 static PyTypeObject Foo_Type = {
2403 PyVarObject_HEAD_INIT(NULL, 0)
2404 "foo.foo",
2405 };
2406 ''', more_init = '''
2407 Foo_Type.tp_flags = Py_TPFLAGS_DEFAULT;
2408 Foo_Type.tp_hash = PyObject_HashNotImplemented;
2409 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
2410 ''')
2411 obj = module.new_obj()
2412 raises(TypeError, hash, obj)
2413 assert type(obj).__dict__['__hash__'] is None
2414 # this is equivalent to
2415 from collections.abc import Hashable
2416 assert not isinstance(obj, Hashable)
2417
2418
2419 def test_has_subclass_flag(self):
2420 module = self.import_extension('foo', [
2421 ("test_flags", "METH_VARARGS",
2422 '''
2423 long long in_flag, my_flag;
2424 PyObject * obj;
2425 if (!PyArg_ParseTuple(args, "OL", &obj, &in_flag))
2426 return NULL;
2427 if (!PyType_Check(obj))
2428 {
2429 PyErr_SetString(PyExc_ValueError, "input must be type");
2430 return NULL;
2431 }
2432 my_flag = ((PyTypeObject*)obj)->tp_flags;
2433 if ((my_flag & in_flag) != in_flag)
2434 return PyLong_FromLong(-1);
2435 if (!PyType_CheckExact(obj)) {
2436 if ((my_flag & Py_TPFLAGS_TYPE_SUBCLASS) == Py_TPFLAGS_TYPE_SUBCLASS)
2437 return PyLong_FromLong(-2);
2438 }
2439 return PyLong_FromLong(0);
2440 '''),])
2441 # copied from object.h
2442 Py_TPFLAGS_LONG_SUBCLASS = (1<<24)
2443 Py_TPFLAGS_LIST_SUBCLASS = (1<<25)
2444 Py_TPFLAGS_TUPLE_SUBCLASS = (1<<26)
2445 Py_TPFLAGS_BYTES_SUBCLASS = (1<<27)
2446 Py_TPFLAGS_UNICODE_SUBCLASS = (1<<28)
2447 Py_TPFLAGS_DICT_SUBCLASS = (1<<29)
2448 Py_TPFLAGS_BASE_EXC_SUBCLASS = (1<<30)
2449 Py_TPFLAGS_TYPE_SUBCLASS = (1<<31)
2450 for t,f in ((int, Py_TPFLAGS_LONG_SUBCLASS),
2451 (list, Py_TPFLAGS_LIST_SUBCLASS),
2452 (tuple, Py_TPFLAGS_TUPLE_SUBCLASS),
2453 (bytes, Py_TPFLAGS_BYTES_SUBCLASS),
2454 (str, Py_TPFLAGS_UNICODE_SUBCLASS),
2455 (dict, Py_TPFLAGS_DICT_SUBCLASS),
2456 (Exception, Py_TPFLAGS_BASE_EXC_SUBCLASS),
2457 (type, Py_TPFLAGS_TYPE_SUBCLASS),
2458 ):
2459 assert module.test_flags(t, f) == 0
2460 class MyList(list):
2461 pass
2462 assert module.test_flags(MyList, Py_TPFLAGS_LIST_SUBCLASS) == 0
2463
2464 def test_newgetset(self):
2465 # Taken from the yara-python project
2466 module = self.import_extension('foo', [
2467 ('newexc', 'METH_NOARGS',
2468 """
2469 PyObject *YaraWarningError = PyErr_NewException("foo.YaraWarningError", PyExc_Exception, NULL);
2470
2471 PyTypeObject *YaraWarningError_type = (PyTypeObject *) YaraWarningError;
2472 PyObject* descr = PyDescr_NewGetSet(YaraWarningError_type,
2473 YaraWarningError_getsetters);
2474 if (PyDict_SetItem(YaraWarningError_type->tp_dict,
2475 PyDescr_NAME(descr), descr) < 0) {
2476 Py_DECREF(descr);
2477 return NULL;
2478 }
2479 return YaraWarningError;
2480 """),
2481 ], prologue="""
2482 static PyObject* YaraWarningError_getwarnings(PyObject *self, void* closure)
2483 {
2484 PyObject *args = PyObject_GetAttrString(self, "args");
2485 if (!args) {
2486 return NULL;
2487 }
2488
2489 PyObject* ret = PyTuple_GetItem(args, 0);
2490 Py_XINCREF(ret);
2491 Py_XDECREF(args);
2492 return ret;
2493 }
2494
2495 static PyGetSetDef YaraWarningError_getsetters[] = {
2496 {"warnings", YaraWarningError_getwarnings, NULL, NULL, NULL},
2497 {NULL}
2498 };
2499 """)
2500 errtype = module.newexc()
2501 err = errtype("abc")
2502 assert err.warnings == "abc"
2503
2504 def test_heaptype_dealloc(self):
2505 # Taken from https://github.com/wjakob/pypy_issues at commit 03890103
2506 import gc
2507 module = self.import_module(name='nanobind1', filename="nanobind1")
2508 for i in range(100):
2509 module.heap_type()
2510 gc.collect()
2511
2512 def test_heaptype_metaclass(self):
2513 # Taken from https://github.com/wjakob/pypy_issues at commit 03890103
2514 # Fixed so both cases pass in 769acaa69cfe, issue 4013_
2515 module = self.import_module(name='nanobind1', filename="nanobind1")
2516 # 2 vs 3 shenanigans to declare
2517 # class X(object, metaclass=module.metaclass): pass
2518 X = module.metaclass_good('X', (object,), {})
2519 x = X()
2520
2521 X = module.metaclass_bad('X', (object,), {})
2522 x = X()
2523
2524 def test_vectorcall2(self):
2525 # Taken from https://github.com/wjakob/pypy_issues at commit 03890103
2526 # py3.9+ only
2527 module = self.import_module(name='nanobind1', filename="nanobind1")
2528 c = module.callable()
2529 assert c() == 1234
2530
2531 def f(value):
2532 assert value == 1234
2533
2534 module.call(f)
2535
2536 def test_nanobind2_tp_traverse(self):
2537 # Taken from https://github.com/wjakob/pypy_issues at commit 89a8585
2538 import gc
2539 import sys
2540 if sys.implementation.name == 'pypy':
2541 skip("tp_traverse not yet implemented in PyPy")
2542 module = self.import_module(name='nanobind2', filename="nanobind2")
2543 # Create an unreferenced cycle
2544 a = module.wrapper()
2545 a.nested = a
2546 del a
2547 for i in range(5):
2548 gc.collect()
2549 gl = module.global_list
2550 assert gl == ['wrapper tp_init called.',
2551 'wrapper tp_traverse called.',
2552 'wrapper tp_traverse called.',
2553 'wrapper tp_clear called.',
2554 'wrapper tp_dealloc called.',
2555 ]
2556
2557 def test_nanobind2_module_attributes(self):
2558 # Taken from https://github.com/wjakob/pypy_issues at commit 89a8585
2559 import sys
2560 module = self.import_module(name='nanobind2', filename="nanobind2")
2561
2562 f = module.func()
2563 if sys.version_info >= (3, 9) or sys.implementation.name == 'pypy':
2564 assert f.__module__ == "my_module"
2565 else:
2566 assert f.__module__ == "nanobind2"
2567 assert f.__name__ == "my_name"
2568 assert f.__qualname__ == "my_qualname"
2569
2570 def test_nanobind2_vectorcall_method(self):
2571 # Taken from https://github.com/wjakob/pypy_issues at commit 89a8585
2572 module = self.import_module(name='nanobind2', filename="nanobind2")
2573
2574 class A:
2575 def __init__(self):
2576 self.value = 0
2577
2578 def my_method(self, *args, **kwargs):
2579 self.args = args
2580 self.kwargs = kwargs
2581 return "success"
2582
2583 a = A()
2584 assert module.method_call(a) == "success"
2585 assert a.args == (1234,) and a.kwargs == {}
2586 assert module.method_call_kw(a) == "success"
2587 assert a.args == (1234,) and a.kwargs == {"foo" : "bar"}
2588
2589
2590 def unbound_method(*args, **kwargs):
2591 args_value.update(args)
2592 kwargs_value.update(kwargs)
2593 return "unbound"
2594
2595 a.my_method = unbound_method
2596 kwargs_value = {}
2597 args_value = set()
2598
2599
2600 assert module.method_call(a) == "unbound"
2601 assert args_value == set([1234]) and kwargs_value == {}
2602 assert module.method_call_kw(a) == "unbound"
2603 assert args_value == set([1234]) and kwargs_value == {"foo" : "bar"}
2604
2605 def test_nanobind3(self):
2606 module = self.import_module(name='nanobind3', filename="nanobind3")
2607 old_list = module.global_list[:]
2608
2609 o = module.my_object()
2610 c = module.my_callable()
2611
2612 with raises(ValueError):
2613 c(o)
2614
2615 old_list = module.global_list[:]
2616 del o
2617 self.debug_collect() # will call gc.collect unless run untranslated
2618
2619 # Make sure o.tp_dealloc was called
2620 new_list = module.global_list[:]
2621 assert len(new_list) == len(old_list) + 1, "%s %s" %(old_list, new_list)
2622
2623 def test_issubclass(self):
2624 # issue 3976
2625 module = self.import_extension("foo", [
2626 ("issubclass", "METH_VARARGS",
2627 """
2628 PyObject *x = NULL, *y = NULL;
2629 if (!PyArg_ParseTuple(args, "OO", &x, &y)) {
2630 return NULL;
2631 }
2632 if (!PyType_Check(x) | !PyType_Check(y))
2633 return PyLong_FromLong(42);
2634 int subtype = PyType_IsSubtype((PyTypeObject *) x, (PyTypeObject *) y);
2635 return PyLong_FromLong(subtype);
2636 """)])
2637 class Base: pass
2638 class A(Base): pass
2639 class B(Base): pass
2640 assert not issubclass(B, A)
2641 assert not module.issubclass(B, A)
2642 B.__bases__ = (A,)
2643 assert issubclass(B, A)
2644 assert module.issubclass(B, A)
2645
2646 def test_subclass_from_spec(self):
2647 module = self.import_extension("foo", [
2648 ("subclass_from_class", "METH_O",
2649 """
2650 static PyType_Slot HeapType_slots[] = {
2651 {Py_tp_doc, "HeapType()\\n--\\n\\nA type with a signature"},
2652 {0, 0},
2653 };
2654
2655
2656 static PyType_Spec HeapType_spec = {
2657 "module.HeapType",
2658 sizeof(PyObject),
2659 0,
2660 Py_TPFLAGS_DEFAULT,
2661 HeapType_slots
2662 };
2663
2664 return PyType_FromSpecWithBases(&HeapType_spec, args);
2665 """),
2666 ("get_qualname", "METH_O",
2667 """
2668 return PyType_GetQualName((PyTypeObject *)args);
2669 """),
2670 ])
2671
2672 # bool cannot be a base class
2673 with raises(TypeError):
2674 module.subclass_from_class((bool,))
2675
2676 inttype = module.subclass_from_class((int,))
2677
2678 # the type does not set Py_TPFLAGS_BASETYPE, so cannot inherit
2679 with raises(TypeError):
2680 class int2(inttype):
2681 pass
2682
2683 # Make sure the flag passes to app-level
2684 assert isinstance(inttype(), int)
2685
2686 assert module.get_qualname(inttype) == "HeapType"
2687
2688 def test_subclass_from_default(self):
2689 # CPython allows static types to subclass base classes without
2690 # the Py_TPFLAGS_BASETYPE flag
2691 module = self.import_extension('foo', [
2692 ("new_obj", "METH_NOARGS",
2693 '''
2694 PyObject *obj;
2695 obj = PyObject_New(PyObject, &Foo_Type);
2696 return obj;
2697 '''
2698 ),
2699 ("has_tp_call", "METH_O",
2700 """
2701 return PyBool_FromLong((Py_TYPE(args)->tp_call != NULL));
2702 """
2703 )], prologue='''
2704 static PyTypeObject Foo_Type = {
2705 PyVarObject_HEAD_INIT(NULL, 0)
2706 "foo.foo",
2707 };
2708 static PyTypeObject Base_Type = {
2709 PyVarObject_HEAD_INIT(NULL, 0)
2710 "foo.base",
2711 };
2712 ''', more_init = '''
2713 Base_Type.tp_flags = Py_TPFLAGS_DEFAULT;
2714 if (PyType_Ready(&Base_Type) < 0) INITERROR;
2715 Foo_Type.tp_base = &Base_Type;
2716 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
2717 ''')
2718
2719 obj = module.new_obj()
2720 assert str(type(obj).mro()) == "[<class 'foo.foo'>, <class 'foo.base'>, <class 'object'>]"
2721 # Make sure tp_call is not initialized
2722 class C: pass
2723 assert not module.has_tp_call(obj)
2724 assert module.has_tp_call(module.new_obj)
2725 assert not module.has_tp_call(C())
2726
2727 def test_heap_type1(self):
2728 # issue 3318, make sure the name does not include the module
2729 module = self.import_extension("foo", [
2730 ("get_type", "METH_NOARGS",
2731 """
2732 PyType_Slot CustomHeap_Type_slots[] = {
2733 {0, 0},
2734 };
2735
2736 PyType_Spec CustomHeap_Type_spec = {
2737 "custom.CustomHeap",
2738 0,
2739 0,
2740 Py_TPFLAGS_DEFAULT,
2741 CustomHeap_Type_slots,
2742 };
2743 return PyType_FromSpec(&CustomHeap_Type_spec);
2744 """),])
2745 custom = module.get_type()
2746 assert custom.__name__ == "CustomHeap"
2747
2748 def test_heap_type2(self):
2749 # issue 4826: note type->tp_as_buffer is not set (not needed since
2750 # O.__buffer__ does not exist)
2751 module = self.import_extension("foo", [], prologue="""
2752 PyObject *make_new_python_type(PyObject* scope,
2753 const char *full_name, PyTypeObject *base) {
2754 PyHeapTypeObject *heap_type = (PyHeapTypeObject *)PyType_Type.tp_alloc(&PyType_Type, 0);
2755 heap_type->ht_name = PyUnicode_FromString(full_name);
2756
2757 PyTypeObject *type = &heap_type->ht_type;
2758 type->tp_name = full_name;
2759 Py_INCREF(base);
2760 type->tp_base = base;
2761 type->tp_basicsize = 0;
2762 type->tp_as_number = &heap_type->as_number;
2763 type->tp_as_sequence = &heap_type->as_sequence;
2764 type->tp_as_mapping = &heap_type->as_mapping;
2765 type->tp_as_async = &heap_type->as_async;
2766 type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
2767 type->tp_flags |= Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION;
2768 PyType_Ready(type);
2769 PyObject_SetAttrString(scope, full_name, (PyObject*)type);
2770 return (PyObject *) type;
2771 }
2772 """, more_init="""
2773 /* No error checking */
2774 PyObject *op = make_new_python_type(mod, "O", &PyBaseObject_Type);
2775 PyObject *ap = make_new_python_type(mod, "A", (PyTypeObject *) op);
2776 PyObject *bp = make_new_python_type(mod, "B", (PyTypeObject *) op);
2777 PyObject *a_tuple_p = PyTuple_New(1);
2778 PyTuple_SetItem(a_tuple_p, 0, ap);
2779 PyObject_SetAttrString(bp, "__bases__", a_tuple_p);
2780 """)
2781 assert module.B.__bases__ == (module.A,)
2782 with raises(TypeError):
2783 module.B()
2784
2785 # messes with leak detection, leave at the end of the tests
2786 def test_tp_new_in_subclass(self):
2787 import datetime
2788 module = self.import_module(name='foo3')
2789 module.footype("X", (object,), {})
2790 a = module.datetimetype(1, 1, 1)
2791 assert isinstance(a, module.datetimetype)
2792 def test_tp_new_mixin_before_ctype(self):
2793 # A C type with explicit tp_new (like Cython-generated types) must
2794 # still be called when a Python mixin appears BEFORE it in bases:
2795 # class Mixed(PythonMixin, CType): ...
2796 # The bug: find_best_base() returns PythonMixin when both it and CType
2797 # share object's layout (tp_basicsize == sizeof(PyObject)), so
2798 # _find_which_tp_new_to_call() follows PythonMixin.__new__ ->
2799 # object.__new__ and raises TypeError on extra args.
2800 # See https://github.com/pypy/pypy/issues/5418
2801 module = self.import_extension('foo_tp_new_mixin', [
2802 ("get_type", "METH_NOARGS",
2803 '''
2804 Py_INCREF(&Foo_Type);
2805 return (PyObject *)&Foo_Type;
2806 ''')],
2807 prologue='''
2808 static PyObject *
2809 Foo_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
2810 /* tp_new that accepts any args, like Cython-generated types */
2811 return type->tp_alloc(type, 0);
2812 }
2813 static PyTypeObject Foo_Type = {
2814 PyVarObject_HEAD_INIT(NULL, 0)
2815 "foo_tp_new_mixin.Foo", /* tp_name */
2816 sizeof(PyObject), /* tp_basicsize: same as PyObject -> shares object layout */
2817 0, /* tp_itemsize */
2818 0, /* tp_dealloc */
2819 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2820 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
2821 };
2822 ''',
2823 more_init='''
2824 Foo_Type.tp_new = Foo_new;
2825 if (PyType_Ready(&Foo_Type) < 0) INITERROR;
2826 ''')
2827 CBase = module.get_type()
2828 assert CBase.__new__ is not object.__new__
2829
2830 class PythonMixin:
2831 pass
2832
2833 class Mixed(PythonMixin, CBase):
2834 def __init__(self, value):
2835 self.value = value
2836
2837 class SubMixed(Mixed):
2838 pass
2839
2840 # Must call Foo_new (not object.__new__) even with extra args
2841 obj = Mixed(42)
2842 assert obj.value == 42
2843 obj2 = SubMixed(99)
2844 assert obj2.value == 99
2845
2846 def test_tp_new_mixin_intermediate_python_class(self):
2847 # Like test_tp_new_mixin_with_struct_backing but with an intermediate
2848 # Python class between the user's class and the C extension type,
2849 # mimicking the pandas hierarchy:
2850 # NumpyBlock(BlockPython) where BlockPython(Mixin, CBase)
2851 # MRO: [NumpyBlock, BlockPython, Mixin, CBase, object]
2852 # This exercises the two-level recursion in _find_which_tp_new_to_call:
2853 # NumpyBlock -> best_base=BlockPython -> lookup finds CBase.__new__
2854 # -> recurse into BlockPython -> best_base=CBase -> terminate
2855 module = self.import_extension('foo_tp_new_interm', [
2856 ("get_type", "METH_NOARGS",
2857 '''
2858 Py_INCREF(&FooInterm_Type);
2859 return (PyObject *)&FooInterm_Type;
2860 ''')],
2861 prologue='''
2862 typedef struct {
2863 PyObject ob_base;
2864 int extra_field;
2865 int extra_field2;
2866 } FooIntermObject;
2867
2868 static PyObject *
2869 FooInterm_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
2870 FooIntermObject *obj = (FooIntermObject *) type->tp_alloc(type, 0);
2871 if (!obj) return NULL;
2872 obj->extra_field = 42;
2873 obj->extra_field2 = 99;
2874 /* Trigger create_ref path like BlockValuesRefs_add_reference */
2875 PyObject *attr = PyUnicode_FromString("__class__");
2876 if (!attr) { Py_DECREF(obj); return NULL; }
2877 PyObject *cls = PyObject_GetAttr((PyObject*)obj, attr);
2878 Py_DECREF(attr);
2879 if (!cls) { Py_DECREF(obj); return NULL; }
2880 Py_DECREF(cls);
2881 return (PyObject*)obj;
2882 }
2883 static void
2884 FooInterm_dealloc(FooIntermObject *op) {
2885 Py_TYPE(op)->tp_free(op);
2886 }
2887 static PyTypeObject FooInterm_Type = {
2888 PyVarObject_HEAD_INIT(NULL, 0)
2889 "foo_tp_new_interm.FooInterm", /* tp_name */
2890 sizeof(FooIntermObject), /* tp_basicsize > sizeof(PyObject) */
2891 0, /* tp_itemsize */
2892 (destructor)FooInterm_dealloc, /* tp_dealloc */
2893 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2894 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2895 };
2896 ''',
2897 more_init='''
2898 FooInterm_Type.tp_new = FooInterm_new;
2899 if (PyType_Ready(&FooInterm_Type) < 0) INITERROR;
2900 ''')
2901 CBase = module.get_type()
2902 assert CBase.__new__ is not object.__new__
2903
2904 class Mixin:
2905 pass
2906
2907 # Intermediate Python class (Block_Python analog)
2908 # MRO: [BlockPython, Mixin, CBase, object]
2909 class BlockPython(Mixin, CBase):
2910 pass
2911
2912 # User's instantiated class (NumpyBlock analog)
2913 # MRO: [NumpyBlock, BlockPython, Mixin, CBase, object]
2914 class NumpyBlock(BlockPython):
2915 def __init__(self, value):
2916 self.value = value
2917
2918 # CBase's tp_new must be called with type=NumpyBlock; if tp_basicsize
2919 # is not propagated correctly the two extra_field writes corrupt the heap
2920 obj = NumpyBlock(42)
2921 assert obj.value == 42
2922 obj2 = NumpyBlock(99)
2923 assert obj2.value == 99
2924
2925 def test_tp_new_mixin_with_struct_backing(self):
2926 # Like test_tp_new_mixin_before_ctype but with tp_basicsize >
2927 # sizeof(PyObject). When the C type has its own layout
2928 # (force_new_layout=True), find_best_base() returns the C type rather
2929 # than PythonMixin, so _find_which_tp_new_to_call() takes the
2930 # recursive branch (elif is_tp_new_wrapper) instead of the
2931 # "skip object.__new__" branch.
2932 #
2933 # The tp_new also calls PyObject_GetAttr on the freshly allocated
2934 # object, exercising the cpyext_tp_getattro_object -> create_ref path
2935 # that appears in the pandas crash trace.
2936 module = self.import_extension('foo_tp_new_struct', [
2937 ("get_type", "METH_NOARGS",
2938 '''
2939 Py_INCREF(&FooStruct_Type);
2940 return (PyObject *)&FooStruct_Type;
2941 ''')],
2942 prologue='''
2943 typedef struct {
2944 PyObject ob_base;
2945 int extra_field;
2946 } FooStructObject;
2947
2948 static PyObject *
2949 FooStruct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
2950 FooStructObject *obj = (FooStructObject *) type->tp_alloc(type, 0);
2951 if (!obj) return NULL;
2952 obj->extra_field = 42;
2953 /* Trigger cpyext_tp_getattro_object -> create_ref path */
2954 PyObject *attr = PyUnicode_FromString("__class__");
2955 if (!attr) { Py_DECREF(obj); return NULL; }
2956 PyObject *cls = PyObject_GetAttr((PyObject*)obj, attr);
2957 Py_DECREF(attr);
2958 if (!cls) { Py_DECREF(obj); return NULL; }
2959 Py_DECREF(cls);
2960 return (PyObject*)obj;
2961 }
2962 static void
2963 FooStruct_dealloc(FooStructObject *op) {
2964 Py_TYPE(op)->tp_free(op);
2965 }
2966 static PyTypeObject FooStruct_Type = {
2967 PyVarObject_HEAD_INIT(NULL, 0)
2968 "foo_tp_new_struct.FooStruct", /* tp_name */
2969 sizeof(FooStructObject), /* tp_basicsize > sizeof(PyObject) */
2970 0, /* tp_itemsize */
2971 (destructor)FooStruct_dealloc, /* tp_dealloc */
2972 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2973 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2974 };
2975 ''',
2976 more_init='''
2977 FooStruct_Type.tp_new = FooStruct_new;
2978 if (PyType_Ready(&FooStruct_Type) < 0) INITERROR;
2979 ''')
2980 CBase = module.get_type()
2981 assert CBase.__new__ is not object.__new__
2982
2983 class PythonMixin:
2984 pass
2985
2986 class Mixed(PythonMixin, CBase):
2987 def __init__(self, value):
2988 self.value = value
2989
2990 class SubMixed(Mixed):
2991 pass
2992
2993 obj = Mixed(42)
2994 assert obj.value == 42
2995 obj2 = SubMixed(99)
2996 assert obj2.value == 99
2997
2998 def test_tp_new_mixin_from_spec(self):
2999 # Regression test for the PyType_FromModuleAndSpec / PyType_FromSpecWithBases
3000 # new_layout bug: when flag_heaptype=True (set by the spec API),
3001 # PyPy incorrectly uses sizeof(PyHeapTypeObject) as minsize, so a type
3002 # with basicsize < sizeof(PyHeapTypeObject) gets new_layout=False.
3003 # That makes find_best_base() prefer the Python mixin over the C type,
3004 # so Python subclasses inherit tp_basicsize=24 (object) instead of
3005 # the struct size, causing tp_alloc to under-allocate and writes to
3006 # extra fields corrupt the heap.
3007 #
3008 # Mirrors the pandas pattern:
3009 # libinternals.Block <- PyType_FromSpecWithBases (struct with extra fields)
3010 # Block(PandasObject, libinternals.Block) <- intermediate Python class
3011 # NumpyBlock(Block) <- user-instantiated subclass
3012 module = self.import_extension('foo_spec_mixin', [
3013 ("get_type", "METH_NOARGS",
3014 '''
3015 static PyType_Slot FooSpec_slots[] = {
3016 {Py_tp_new, FooSpec_new},
3017 {Py_tp_dealloc, FooSpec_dealloc},
3018 {0, 0}
3019 };
3020 static PyType_Spec FooSpec_spec = {
3021 "foo_spec_mixin.FooSpec",
3022 sizeof(FooSpecObject),
3023 0,
3024 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
3025 FooSpec_slots
3026 };
3027 PyObject *tp = PyType_FromSpecWithBases(&FooSpec_spec, NULL);
3028 return tp;
3029 ''')],
3030 prologue='''
3031 typedef struct {
3032 PyObject ob_base;
3033 int extra_field;
3034 int extra_field2;
3035 } FooSpecObject;
3036
3037 static PyObject *
3038 FooSpec_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
3039 FooSpecObject *obj = (FooSpecObject *) type->tp_alloc(type, 0);
3040 if (!obj) return NULL;
3041 /* Write to extra fields; if tp_basicsize was not propagated
3042 correctly these writes corrupt the malloc heap. */
3043 obj->extra_field = 111;
3044 obj->extra_field2 = 222;
3045 /* Trigger cpyext_tp_getattro -> create_ref path */
3046 PyObject *attr = PyUnicode_FromString("__class__");
3047 if (!attr) { Py_DECREF(obj); return NULL; }
3048 PyObject *cls = PyObject_GetAttr((PyObject*)obj, attr);
3049 Py_DECREF(attr);
3050 if (!cls) { Py_DECREF(obj); return NULL; }
3051 Py_DECREF(cls);
3052 return (PyObject*)obj;
3053 }
3054 static void
3055 FooSpec_dealloc(FooSpecObject *op) {
3056 Py_TYPE(op)->tp_free(op);
3057 }
3058 ''')
3059 CBase = module.get_type()
3060 # CBase was created via PyType_FromSpecWithBases - it carries
3061 # Py_TPFLAGS_HEAPTYPE; the bug triggers when building the Python
3062 # subclass hierarchy below.
3063 assert CBase.__new__ is not object.__new__
3064
3065 class Mixin:
3066 pass
3067
3068 # Intermediate Python class (pandas Block analog)
3069 class BlockPython(Mixin, CBase):
3070 pass
3071
3072 # User class (pandas NumpyBlock analog)
3073 class NumpyBlock(BlockPython):
3074 def __init__(self, value):
3075 self.value = value
3076
3077 # If tp_basicsize was not propagated, these writes corrupt malloc
3078 # metadata and either crash here or in a later allocation.
3079 obj = NumpyBlock(42)
3080 assert obj.value == 42
3081 obj2 = NumpyBlock(99)
3082 assert obj2.value == 99
3083
3084 def test_multiple_inheritance_ctypes_with_weakref_or_dict(self):
3085 # taken from test_capi test_multiple_inheritance_ctypes_with_weakref_or_dict:
3086 # types created via PyType_FromSpec that carry tp_dictoffset or
3087 # tp_weaklistoffset should be combinable in multiple inheritance
3088 # without raising "instance layout conflicts".
3089 module = self.import_extension('foo_heapctype', [],
3090 prologue="""
3091 #include <structmember.h>
3092
3093 typedef struct {
3094 PyObject_HEAD
3095 PyObject *dict;
3096 } HeapCTypeWithDictObject;
3097
3098 static void
3099 heapctypewithdict_dealloc(HeapCTypeWithDictObject* self)
3100 {
3101 PyTypeObject *tp = Py_TYPE(self);
3102 Py_XDECREF(self->dict);
3103 PyObject_Free(self);
3104 Py_DECREF(tp);
3105 }
3106
3107 static PyGetSetDef heapctypewithdict_getsetlist[] = {
3108 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
3109 {NULL}
3110 };
3111
3112 static struct PyMemberDef heapctypewithdict_members[] = {
3113 {"dictobj", T_OBJECT, offsetof(HeapCTypeWithDictObject, dict)},
3114 {"__dictoffset__", T_PYSSIZET,
3115 offsetof(HeapCTypeWithDictObject, dict), READONLY},
3116 {NULL}
3117 };
3118
3119 static PyType_Slot HeapCTypeWithDict_slots[] = {
3120 {Py_tp_members, heapctypewithdict_members},
3121 {Py_tp_getset, heapctypewithdict_getsetlist},
3122 {Py_tp_dealloc, heapctypewithdict_dealloc},
3123 {0, 0},
3124 };
3125
3126 static PyType_Spec HeapCTypeWithDict_spec = {
3127 "foo_heapctype.HeapCTypeWithDict",
3128 sizeof(HeapCTypeWithDictObject),
3129 0,
3130 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
3131 HeapCTypeWithDict_slots
3132 };
3133
3134 static PyType_Spec HeapCTypeWithDict2_spec = {
3135 "foo_heapctype.HeapCTypeWithDict2",
3136 sizeof(HeapCTypeWithDictObject),
3137 0,
3138 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
3139 HeapCTypeWithDict_slots
3140 };
3141
3142 typedef struct {
3143 PyObject_HEAD
3144 PyObject *weakreflist;
3145 } HeapCTypeWithWeakrefObject;
3146
3147 static struct PyMemberDef heapctypewithweakref_members[] = {
3148 {"weakreflist", T_OBJECT,
3149 offsetof(HeapCTypeWithWeakrefObject, weakreflist)},
3150 {"__weaklistoffset__", T_PYSSIZET,
3151 offsetof(HeapCTypeWithWeakrefObject, weakreflist), READONLY},
3152 {NULL}
3153 };
3154
3155 static void
3156 heapctypewithweakref_dealloc(HeapCTypeWithWeakrefObject* self)
3157 {
3158 PyTypeObject *tp = Py_TYPE(self);
3159 if (self->weakreflist != NULL)
3160 PyObject_ClearWeakRefs((PyObject *) self);
3161 Py_XDECREF(self->weakreflist);
3162 PyObject_Free(self);
3163 Py_DECREF(tp);
3164 }
3165
3166 static PyType_Slot HeapCTypeWithWeakref_slots[] = {
3167 {Py_tp_members, heapctypewithweakref_members},
3168 {Py_tp_dealloc, heapctypewithweakref_dealloc},
3169 {0, 0},
3170 };
3171
3172 static PyType_Spec HeapCTypeWithWeakref_spec = {
3173 "foo_heapctype.HeapCTypeWithWeakref",
3174 sizeof(HeapCTypeWithWeakrefObject),
3175 0,
3176 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
3177 HeapCTypeWithWeakref_slots
3178 };
3179
3180 static PyType_Spec HeapCTypeWithWeakref2_spec = {
3181 "foo_heapctype.HeapCTypeWithWeakref2",
3182 sizeof(HeapCTypeWithWeakrefObject),
3183 0,
3184 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
3185 HeapCTypeWithWeakref_slots
3186 };
3187 """,
3188 more_init="""
3189 PyObject *t;
3190 #define ADD_TYPE(spec, name) \\
3191 t = PyType_FromSpec(spec); \\
3192 if (t == NULL) INITERROR; \\
3193 PyModule_AddObject(mod, name, t);
3194 ADD_TYPE(&HeapCTypeWithDict_spec, "HeapCTypeWithDict");
3195 ADD_TYPE(&HeapCTypeWithDict2_spec, "HeapCTypeWithDict2");
3196 ADD_TYPE(&HeapCTypeWithWeakref_spec, "HeapCTypeWithWeakref");
3197 ADD_TYPE(&HeapCTypeWithWeakref2_spec, "HeapCTypeWithWeakref2");
3198 #undef ADD_TYPE
3199 """)
3200 class Both1(module.HeapCTypeWithWeakref, module.HeapCTypeWithDict):
3201 pass
3202 class Both2(module.HeapCTypeWithDict, module.HeapCTypeWithWeakref):
3203 pass
3204 for cls in (module.HeapCTypeWithDict, module.HeapCTypeWithDict2,
3205 module.HeapCTypeWithWeakref, module.HeapCTypeWithWeakref2):
3206 for cls2 in (module.HeapCTypeWithDict, module.HeapCTypeWithDict2,
3207 module.HeapCTypeWithWeakref, module.HeapCTypeWithWeakref2):
3208 if cls is not cls2:
3209 class S(cls, cls2):
3210 pass
3211 class B1(Both1, cls):
3212 pass
3213 class B2(Both2, cls):
3214 pass