spacepaste

  1.  
  2. def test_getset(self):
  3. module = self.import_extension('foo', [
  4. ("get_instance", "METH_NOARGS",
  5. '''
  6. return PyObject_New(PyObject, &Foo_Type);
  7. '''
  8. ), ("get_number", "METH_NOARGS",
  9. '''
  10. return PyInt_FromLong(my_global_number);
  11. '''
  12. )], prologue='''
  13. #if PY_MAJOR_VERSION > 2
  14. #define PyInt_FromLong PyLong_FromLong
  15. #endif
  16. static long my_global_number;
  17. static PyTypeObject Foo_Type = {
  18. PyVarObject_HEAD_INIT(NULL, 0)
  19. "foo.foo",
  20. };
  21. static PyObject *bar_get(PyObject *foo, void *closure)
  22. {
  23. return PyInt_FromLong(1000 + (long)closure);
  24. }
  25. static PyObject *baz_get(PyObject *foo, void *closure)
  26. {
  27. return PyInt_FromLong(2000 + (long)closure);
  28. }
  29. static int baz_set(PyObject *foo, PyObject *x, void *closure)
  30. {
  31. if (x != NULL)
  32. my_global_number = 3000 + (long)closure + PyInt_AsLong(x);
  33. else
  34. my_global_number = 4000 + (long)closure;
  35. return 0;
  36. }
  37. static PyGetSetDef foo_getset[] = {
  38. { "bar", bar_get, NULL, "mybardoc", (void *)42 },
  39. { "baz", baz_get, baz_set, "mybazdoc", (void *)43 },
  40. { NULL }
  41. };
  42. ''', more_init = '''
  43. Foo_Type.tp_getset = foo_getset;
  44. Foo_Type.tp_flags = Py_TPFLAGS_DEFAULT;
  45. if (PyType_Ready(&Foo_Type) < 0) INITERROR;
  46. ''')
  47. foo = module.get_instance()
  48. assert foo.bar == 1042
  49. assert foo.bar == 1042
  50. assert foo.baz == 2043
  51. foo.baz = 50000
  52. assert module.get_number() == 53043
  53. foo.bar = 0
  54. raises(AttributeError, "foo.bar = 0")
  55. del foo.baz
  56. assert module.get_number() == 4043
  57. raises(AttributeError, "del foo.bar")
  58.