PageRenderTime 84ms CodeModel.GetById 31ms app.highlight 42ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/descrobject.c

https://bitbucket.org/mirror/cpython/
C | 1661 lines | 1424 code | 180 blank | 57 comment | 190 complexity | 9bd35c395c4d32e020c50dac70067372 MD5 | raw file
Possible License(s): Unlicense, 0BSD, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

   1/* Descriptors -- a new, flexible way to describe attributes */
   2
   3#include "Python.h"
   4#include "structmember.h" /* Why is this not included in Python.h? */
   5
   6static void
   7descr_dealloc(PyDescrObject *descr)
   8{
   9    _PyObject_GC_UNTRACK(descr);
  10    Py_XDECREF(descr->d_type);
  11    Py_XDECREF(descr->d_name);
  12    Py_XDECREF(descr->d_qualname);
  13    PyObject_GC_Del(descr);
  14}
  15
  16static PyObject *
  17descr_name(PyDescrObject *descr)
  18{
  19    if (descr->d_name != NULL && PyUnicode_Check(descr->d_name))
  20        return descr->d_name;
  21    return NULL;
  22}
  23
  24static PyObject *
  25descr_repr(PyDescrObject *descr, const char *format)
  26{
  27    PyObject *name = NULL;
  28    if (descr->d_name != NULL && PyUnicode_Check(descr->d_name))
  29        name = descr->d_name;
  30
  31    return PyUnicode_FromFormat(format, name, "?", descr->d_type->tp_name);
  32}
  33
  34static PyObject *
  35method_repr(PyMethodDescrObject *descr)
  36{
  37    return descr_repr((PyDescrObject *)descr,
  38                      "<method '%V' of '%s' objects>");
  39}
  40
  41static PyObject *
  42member_repr(PyMemberDescrObject *descr)
  43{
  44    return descr_repr((PyDescrObject *)descr,
  45                      "<member '%V' of '%s' objects>");
  46}
  47
  48static PyObject *
  49getset_repr(PyGetSetDescrObject *descr)
  50{
  51    return descr_repr((PyDescrObject *)descr,
  52                      "<attribute '%V' of '%s' objects>");
  53}
  54
  55static PyObject *
  56wrapperdescr_repr(PyWrapperDescrObject *descr)
  57{
  58    return descr_repr((PyDescrObject *)descr,
  59                      "<slot wrapper '%V' of '%s' objects>");
  60}
  61
  62static int
  63descr_check(PyDescrObject *descr, PyObject *obj, PyObject **pres)
  64{
  65    if (obj == NULL) {
  66        Py_INCREF(descr);
  67        *pres = (PyObject *)descr;
  68        return 1;
  69    }
  70    if (!PyObject_TypeCheck(obj, descr->d_type)) {
  71        PyErr_Format(PyExc_TypeError,
  72                     "descriptor '%V' for '%s' objects "
  73                     "doesn't apply to '%s' object",
  74                     descr_name((PyDescrObject *)descr), "?",
  75                     descr->d_type->tp_name,
  76                     obj->ob_type->tp_name);
  77        *pres = NULL;
  78        return 1;
  79    }
  80    return 0;
  81}
  82
  83static PyObject *
  84classmethod_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type)
  85{
  86    /* Ensure a valid type.  Class methods ignore obj. */
  87    if (type == NULL) {
  88        if (obj != NULL)
  89            type = (PyObject *)obj->ob_type;
  90        else {
  91            /* Wot - no type?! */
  92            PyErr_Format(PyExc_TypeError,
  93                         "descriptor '%V' for type '%s' "
  94                         "needs either an object or a type",
  95                         descr_name((PyDescrObject *)descr), "?",
  96                         PyDescr_TYPE(descr)->tp_name);
  97            return NULL;
  98        }
  99    }
 100    if (!PyType_Check(type)) {
 101        PyErr_Format(PyExc_TypeError,
 102                     "descriptor '%V' for type '%s' "
 103                     "needs a type, not a '%s' as arg 2",
 104                     descr_name((PyDescrObject *)descr), "?",
 105                     PyDescr_TYPE(descr)->tp_name,
 106                     type->ob_type->tp_name);
 107        return NULL;
 108    }
 109    if (!PyType_IsSubtype((PyTypeObject *)type, PyDescr_TYPE(descr))) {
 110        PyErr_Format(PyExc_TypeError,
 111                     "descriptor '%V' for type '%s' "
 112                     "doesn't apply to type '%s'",
 113                     descr_name((PyDescrObject *)descr), "?",
 114                     PyDescr_TYPE(descr)->tp_name,
 115                     ((PyTypeObject *)type)->tp_name);
 116        return NULL;
 117    }
 118    return PyCFunction_NewEx(descr->d_method, type, NULL);
 119}
 120
 121static PyObject *
 122method_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type)
 123{
 124    PyObject *res;
 125
 126    if (descr_check((PyDescrObject *)descr, obj, &res))
 127        return res;
 128    return PyCFunction_NewEx(descr->d_method, obj, NULL);
 129}
 130
 131static PyObject *
 132member_get(PyMemberDescrObject *descr, PyObject *obj, PyObject *type)
 133{
 134    PyObject *res;
 135
 136    if (descr_check((PyDescrObject *)descr, obj, &res))
 137        return res;
 138    return PyMember_GetOne((char *)obj, descr->d_member);
 139}
 140
 141static PyObject *
 142getset_get(PyGetSetDescrObject *descr, PyObject *obj, PyObject *type)
 143{
 144    PyObject *res;
 145
 146    if (descr_check((PyDescrObject *)descr, obj, &res))
 147        return res;
 148    if (descr->d_getset->get != NULL)
 149        return descr->d_getset->get(obj, descr->d_getset->closure);
 150    PyErr_Format(PyExc_AttributeError,
 151                 "attribute '%V' of '%.100s' objects is not readable",
 152                 descr_name((PyDescrObject *)descr), "?",
 153                 PyDescr_TYPE(descr)->tp_name);
 154    return NULL;
 155}
 156
 157static PyObject *
 158wrapperdescr_get(PyWrapperDescrObject *descr, PyObject *obj, PyObject *type)
 159{
 160    PyObject *res;
 161
 162    if (descr_check((PyDescrObject *)descr, obj, &res))
 163        return res;
 164    return PyWrapper_New((PyObject *)descr, obj);
 165}
 166
 167static int
 168descr_setcheck(PyDescrObject *descr, PyObject *obj, PyObject *value,
 169               int *pres)
 170{
 171    assert(obj != NULL);
 172    if (!PyObject_TypeCheck(obj, descr->d_type)) {
 173        PyErr_Format(PyExc_TypeError,
 174                     "descriptor '%V' for '%.100s' objects "
 175                     "doesn't apply to '%.100s' object",
 176                     descr_name(descr), "?",
 177                     descr->d_type->tp_name,
 178                     obj->ob_type->tp_name);
 179        *pres = -1;
 180        return 1;
 181    }
 182    return 0;
 183}
 184
 185static int
 186member_set(PyMemberDescrObject *descr, PyObject *obj, PyObject *value)
 187{
 188    int res;
 189
 190    if (descr_setcheck((PyDescrObject *)descr, obj, value, &res))
 191        return res;
 192    return PyMember_SetOne((char *)obj, descr->d_member, value);
 193}
 194
 195static int
 196getset_set(PyGetSetDescrObject *descr, PyObject *obj, PyObject *value)
 197{
 198    int res;
 199
 200    if (descr_setcheck((PyDescrObject *)descr, obj, value, &res))
 201        return res;
 202    if (descr->d_getset->set != NULL)
 203        return descr->d_getset->set(obj, value,
 204                                    descr->d_getset->closure);
 205    PyErr_Format(PyExc_AttributeError,
 206                 "attribute '%V' of '%.100s' objects is not writable",
 207                 descr_name((PyDescrObject *)descr), "?",
 208                 PyDescr_TYPE(descr)->tp_name);
 209    return -1;
 210}
 211
 212static PyObject *
 213methoddescr_call(PyMethodDescrObject *descr, PyObject *args, PyObject *kwds)
 214{
 215    Py_ssize_t argc;
 216    PyObject *self, *func, *result;
 217
 218    /* Make sure that the first argument is acceptable as 'self' */
 219    assert(PyTuple_Check(args));
 220    argc = PyTuple_GET_SIZE(args);
 221    if (argc < 1) {
 222        PyErr_Format(PyExc_TypeError,
 223                     "descriptor '%V' of '%.100s' "
 224                     "object needs an argument",
 225                     descr_name((PyDescrObject *)descr), "?",
 226                     PyDescr_TYPE(descr)->tp_name);
 227        return NULL;
 228    }
 229    self = PyTuple_GET_ITEM(args, 0);
 230    if (!_PyObject_RealIsSubclass((PyObject *)Py_TYPE(self),
 231                                  (PyObject *)PyDescr_TYPE(descr))) {
 232        PyErr_Format(PyExc_TypeError,
 233                     "descriptor '%V' "
 234                     "requires a '%.100s' object "
 235                     "but received a '%.100s'",
 236                     descr_name((PyDescrObject *)descr), "?",
 237                     PyDescr_TYPE(descr)->tp_name,
 238                     self->ob_type->tp_name);
 239        return NULL;
 240    }
 241
 242    func = PyCFunction_NewEx(descr->d_method, self, NULL);
 243    if (func == NULL)
 244        return NULL;
 245    args = PyTuple_GetSlice(args, 1, argc);
 246    if (args == NULL) {
 247        Py_DECREF(func);
 248        return NULL;
 249    }
 250    result = PyEval_CallObjectWithKeywords(func, args, kwds);
 251    Py_DECREF(args);
 252    Py_DECREF(func);
 253    return result;
 254}
 255
 256static PyObject *
 257classmethoddescr_call(PyMethodDescrObject *descr, PyObject *args,
 258                      PyObject *kwds)
 259{
 260    Py_ssize_t argc;
 261    PyObject *self, *func, *result;
 262
 263    /* Make sure that the first argument is acceptable as 'self' */
 264    assert(PyTuple_Check(args));
 265    argc = PyTuple_GET_SIZE(args);
 266    if (argc < 1) {
 267        PyErr_Format(PyExc_TypeError,
 268                     "descriptor '%V' of '%.100s' "
 269                     "object needs an argument",
 270                     descr_name((PyDescrObject *)descr), "?",
 271                     PyDescr_TYPE(descr)->tp_name);
 272        return NULL;
 273    }
 274    self = PyTuple_GET_ITEM(args, 0);
 275    if (!PyType_Check(self)) {
 276        PyErr_Format(PyExc_TypeError,
 277                     "descriptor '%V' requires a type "
 278                     "but received a '%.100s'",
 279                     descr_name((PyDescrObject *)descr), "?",
 280                     PyDescr_TYPE(descr)->tp_name,
 281                     self->ob_type->tp_name);
 282        return NULL;
 283    }
 284    if (!PyType_IsSubtype((PyTypeObject *)self, PyDescr_TYPE(descr))) {
 285        PyErr_Format(PyExc_TypeError,
 286                     "descriptor '%V' "
 287                     "requires a subtype of '%.100s' "
 288                     "but received '%.100s",
 289                     descr_name((PyDescrObject *)descr), "?",
 290                     PyDescr_TYPE(descr)->tp_name,
 291                     self->ob_type->tp_name);
 292        return NULL;
 293    }
 294
 295    func = PyCFunction_NewEx(descr->d_method, self, NULL);
 296    if (func == NULL)
 297        return NULL;
 298    args = PyTuple_GetSlice(args, 1, argc);
 299    if (args == NULL) {
 300        Py_DECREF(func);
 301        return NULL;
 302    }
 303    result = PyEval_CallObjectWithKeywords(func, args, kwds);
 304    Py_DECREF(func);
 305    Py_DECREF(args);
 306    return result;
 307}
 308
 309static PyObject *
 310wrapperdescr_call(PyWrapperDescrObject *descr, PyObject *args, PyObject *kwds)
 311{
 312    Py_ssize_t argc;
 313    PyObject *self, *func, *result;
 314
 315    /* Make sure that the first argument is acceptable as 'self' */
 316    assert(PyTuple_Check(args));
 317    argc = PyTuple_GET_SIZE(args);
 318    if (argc < 1) {
 319        PyErr_Format(PyExc_TypeError,
 320                     "descriptor '%V' of '%.100s' "
 321                     "object needs an argument",
 322                     descr_name((PyDescrObject *)descr), "?",
 323                     PyDescr_TYPE(descr)->tp_name);
 324        return NULL;
 325    }
 326    self = PyTuple_GET_ITEM(args, 0);
 327    if (!_PyObject_RealIsSubclass((PyObject *)Py_TYPE(self),
 328                                  (PyObject *)PyDescr_TYPE(descr))) {
 329        PyErr_Format(PyExc_TypeError,
 330                     "descriptor '%V' "
 331                     "requires a '%.100s' object "
 332                     "but received a '%.100s'",
 333                     descr_name((PyDescrObject *)descr), "?",
 334                     PyDescr_TYPE(descr)->tp_name,
 335                     self->ob_type->tp_name);
 336        return NULL;
 337    }
 338
 339    func = PyWrapper_New((PyObject *)descr, self);
 340    if (func == NULL)
 341        return NULL;
 342    args = PyTuple_GetSlice(args, 1, argc);
 343    if (args == NULL) {
 344        Py_DECREF(func);
 345        return NULL;
 346    }
 347    result = PyEval_CallObjectWithKeywords(func, args, kwds);
 348    Py_DECREF(args);
 349    Py_DECREF(func);
 350    return result;
 351}
 352
 353static PyObject *
 354method_get_doc(PyMethodDescrObject *descr, void *closure)
 355{
 356    return _PyType_GetDocFromInternalDoc(descr->d_method->ml_name, descr->d_method->ml_doc);
 357}
 358
 359static PyObject *
 360method_get_text_signature(PyMethodDescrObject *descr, void *closure)
 361{
 362    return _PyType_GetTextSignatureFromInternalDoc(descr->d_method->ml_name, descr->d_method->ml_doc);
 363}
 364
 365static PyObject *
 366calculate_qualname(PyDescrObject *descr)
 367{
 368    PyObject *type_qualname, *res;
 369    _Py_IDENTIFIER(__qualname__);
 370
 371    if (descr->d_name == NULL || !PyUnicode_Check(descr->d_name)) {
 372        PyErr_SetString(PyExc_TypeError,
 373                        "<descriptor>.__name__ is not a unicode object");
 374        return NULL;
 375    }
 376
 377    type_qualname = _PyObject_GetAttrId((PyObject *)descr->d_type,
 378                                        &PyId___qualname__);
 379    if (type_qualname == NULL)
 380        return NULL;
 381
 382    if (!PyUnicode_Check(type_qualname)) {
 383        PyErr_SetString(PyExc_TypeError, "<descriptor>.__objclass__."
 384                        "__qualname__ is not a unicode object");
 385        Py_XDECREF(type_qualname);
 386        return NULL;
 387    }
 388
 389    res = PyUnicode_FromFormat("%S.%S", type_qualname, descr->d_name);
 390    Py_DECREF(type_qualname);
 391    return res;
 392}
 393
 394static PyObject *
 395descr_get_qualname(PyDescrObject *descr)
 396{
 397    if (descr->d_qualname == NULL)
 398        descr->d_qualname = calculate_qualname(descr);
 399    Py_XINCREF(descr->d_qualname);
 400    return descr->d_qualname;
 401}
 402
 403static PyObject *
 404descr_reduce(PyDescrObject *descr)
 405{
 406    PyObject *builtins;
 407    PyObject *getattr;
 408    _Py_IDENTIFIER(getattr);
 409
 410    builtins = PyEval_GetBuiltins();
 411    getattr = _PyDict_GetItemId(builtins, &PyId_getattr);
 412    return Py_BuildValue("O(OO)", getattr, PyDescr_TYPE(descr),
 413                         PyDescr_NAME(descr));
 414}
 415
 416static PyMethodDef descr_methods[] = {
 417    {"__reduce__", (PyCFunction)descr_reduce, METH_NOARGS, NULL},
 418    {NULL, NULL}
 419};
 420
 421static PyMemberDef descr_members[] = {
 422    {"__objclass__", T_OBJECT, offsetof(PyDescrObject, d_type), READONLY},
 423    {"__name__", T_OBJECT, offsetof(PyDescrObject, d_name), READONLY},
 424    {0}
 425};
 426
 427static PyGetSetDef method_getset[] = {
 428    {"__doc__", (getter)method_get_doc},
 429    {"__qualname__", (getter)descr_get_qualname},
 430    {"__text_signature__", (getter)method_get_text_signature},
 431    {0}
 432};
 433
 434static PyObject *
 435member_get_doc(PyMemberDescrObject *descr, void *closure)
 436{
 437    if (descr->d_member->doc == NULL) {
 438        Py_INCREF(Py_None);
 439        return Py_None;
 440    }
 441    return PyUnicode_FromString(descr->d_member->doc);
 442}
 443
 444static PyGetSetDef member_getset[] = {
 445    {"__doc__", (getter)member_get_doc},
 446    {"__qualname__", (getter)descr_get_qualname},
 447    {0}
 448};
 449
 450static PyObject *
 451getset_get_doc(PyGetSetDescrObject *descr, void *closure)
 452{
 453    if (descr->d_getset->doc == NULL) {
 454        Py_INCREF(Py_None);
 455        return Py_None;
 456    }
 457    return PyUnicode_FromString(descr->d_getset->doc);
 458}
 459
 460static PyGetSetDef getset_getset[] = {
 461    {"__doc__", (getter)getset_get_doc},
 462    {"__qualname__", (getter)descr_get_qualname},
 463    {0}
 464};
 465
 466static PyObject *
 467wrapperdescr_get_doc(PyWrapperDescrObject *descr, void *closure)
 468{
 469    return _PyType_GetDocFromInternalDoc(descr->d_base->name, descr->d_base->doc);
 470}
 471
 472static PyObject *
 473wrapperdescr_get_text_signature(PyWrapperDescrObject *descr, void *closure)
 474{
 475    return _PyType_GetTextSignatureFromInternalDoc(descr->d_base->name, descr->d_base->doc);
 476}
 477
 478static PyGetSetDef wrapperdescr_getset[] = {
 479    {"__doc__", (getter)wrapperdescr_get_doc},
 480    {"__qualname__", (getter)descr_get_qualname},
 481    {"__text_signature__", (getter)wrapperdescr_get_text_signature},
 482    {0}
 483};
 484
 485static int
 486descr_traverse(PyObject *self, visitproc visit, void *arg)
 487{
 488    PyDescrObject *descr = (PyDescrObject *)self;
 489    Py_VISIT(descr->d_type);
 490    return 0;
 491}
 492
 493PyTypeObject PyMethodDescr_Type = {
 494    PyVarObject_HEAD_INIT(&PyType_Type, 0)
 495    "method_descriptor",
 496    sizeof(PyMethodDescrObject),
 497    0,
 498    (destructor)descr_dealloc,                  /* tp_dealloc */
 499    0,                                          /* tp_print */
 500    0,                                          /* tp_getattr */
 501    0,                                          /* tp_setattr */
 502    0,                                          /* tp_reserved */
 503    (reprfunc)method_repr,                      /* tp_repr */
 504    0,                                          /* tp_as_number */
 505    0,                                          /* tp_as_sequence */
 506    0,                                          /* tp_as_mapping */
 507    0,                                          /* tp_hash */
 508    (ternaryfunc)methoddescr_call,              /* tp_call */
 509    0,                                          /* tp_str */
 510    PyObject_GenericGetAttr,                    /* tp_getattro */
 511    0,                                          /* tp_setattro */
 512    0,                                          /* tp_as_buffer */
 513    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
 514    0,                                          /* tp_doc */
 515    descr_traverse,                             /* tp_traverse */
 516    0,                                          /* tp_clear */
 517    0,                                          /* tp_richcompare */
 518    0,                                          /* tp_weaklistoffset */
 519    0,                                          /* tp_iter */
 520    0,                                          /* tp_iternext */
 521    descr_methods,                              /* tp_methods */
 522    descr_members,                              /* tp_members */
 523    method_getset,                              /* tp_getset */
 524    0,                                          /* tp_base */
 525    0,                                          /* tp_dict */
 526    (descrgetfunc)method_get,                   /* tp_descr_get */
 527    0,                                          /* tp_descr_set */
 528};
 529
 530/* This is for METH_CLASS in C, not for "f = classmethod(f)" in Python! */
 531PyTypeObject PyClassMethodDescr_Type = {
 532    PyVarObject_HEAD_INIT(&PyType_Type, 0)
 533    "classmethod_descriptor",
 534    sizeof(PyMethodDescrObject),
 535    0,
 536    (destructor)descr_dealloc,                  /* tp_dealloc */
 537    0,                                          /* tp_print */
 538    0,                                          /* tp_getattr */
 539    0,                                          /* tp_setattr */
 540    0,                                          /* tp_reserved */
 541    (reprfunc)method_repr,                      /* tp_repr */
 542    0,                                          /* tp_as_number */
 543    0,                                          /* tp_as_sequence */
 544    0,                                          /* tp_as_mapping */
 545    0,                                          /* tp_hash */
 546    (ternaryfunc)classmethoddescr_call,         /* tp_call */
 547    0,                                          /* tp_str */
 548    PyObject_GenericGetAttr,                    /* tp_getattro */
 549    0,                                          /* tp_setattro */
 550    0,                                          /* tp_as_buffer */
 551    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
 552    0,                                          /* tp_doc */
 553    descr_traverse,                             /* tp_traverse */
 554    0,                                          /* tp_clear */
 555    0,                                          /* tp_richcompare */
 556    0,                                          /* tp_weaklistoffset */
 557    0,                                          /* tp_iter */
 558    0,                                          /* tp_iternext */
 559    descr_methods,                              /* tp_methods */
 560    descr_members,                              /* tp_members */
 561    method_getset,                              /* tp_getset */
 562    0,                                          /* tp_base */
 563    0,                                          /* tp_dict */
 564    (descrgetfunc)classmethod_get,              /* tp_descr_get */
 565    0,                                          /* tp_descr_set */
 566};
 567
 568PyTypeObject PyMemberDescr_Type = {
 569    PyVarObject_HEAD_INIT(&PyType_Type, 0)
 570    "member_descriptor",
 571    sizeof(PyMemberDescrObject),
 572    0,
 573    (destructor)descr_dealloc,                  /* tp_dealloc */
 574    0,                                          /* tp_print */
 575    0,                                          /* tp_getattr */
 576    0,                                          /* tp_setattr */
 577    0,                                          /* tp_reserved */
 578    (reprfunc)member_repr,                      /* tp_repr */
 579    0,                                          /* tp_as_number */
 580    0,                                          /* tp_as_sequence */
 581    0,                                          /* tp_as_mapping */
 582    0,                                          /* tp_hash */
 583    0,                                          /* tp_call */
 584    0,                                          /* tp_str */
 585    PyObject_GenericGetAttr,                    /* tp_getattro */
 586    0,                                          /* tp_setattro */
 587    0,                                          /* tp_as_buffer */
 588    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
 589    0,                                          /* tp_doc */
 590    descr_traverse,                             /* tp_traverse */
 591    0,                                          /* tp_clear */
 592    0,                                          /* tp_richcompare */
 593    0,                                          /* tp_weaklistoffset */
 594    0,                                          /* tp_iter */
 595    0,                                          /* tp_iternext */
 596    descr_methods,                              /* tp_methods */
 597    descr_members,                              /* tp_members */
 598    member_getset,                              /* tp_getset */
 599    0,                                          /* tp_base */
 600    0,                                          /* tp_dict */
 601    (descrgetfunc)member_get,                   /* tp_descr_get */
 602    (descrsetfunc)member_set,                   /* tp_descr_set */
 603};
 604
 605PyTypeObject PyGetSetDescr_Type = {
 606    PyVarObject_HEAD_INIT(&PyType_Type, 0)
 607    "getset_descriptor",
 608    sizeof(PyGetSetDescrObject),
 609    0,
 610    (destructor)descr_dealloc,                  /* tp_dealloc */
 611    0,                                          /* tp_print */
 612    0,                                          /* tp_getattr */
 613    0,                                          /* tp_setattr */
 614    0,                                          /* tp_reserved */
 615    (reprfunc)getset_repr,                      /* tp_repr */
 616    0,                                          /* tp_as_number */
 617    0,                                          /* tp_as_sequence */
 618    0,                                          /* tp_as_mapping */
 619    0,                                          /* tp_hash */
 620    0,                                          /* tp_call */
 621    0,                                          /* tp_str */
 622    PyObject_GenericGetAttr,                    /* tp_getattro */
 623    0,                                          /* tp_setattro */
 624    0,                                          /* tp_as_buffer */
 625    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
 626    0,                                          /* tp_doc */
 627    descr_traverse,                             /* tp_traverse */
 628    0,                                          /* tp_clear */
 629    0,                                          /* tp_richcompare */
 630    0,                                          /* tp_weaklistoffset */
 631    0,                                          /* tp_iter */
 632    0,                                          /* tp_iternext */
 633    0,                                          /* tp_methods */
 634    descr_members,                              /* tp_members */
 635    getset_getset,                              /* tp_getset */
 636    0,                                          /* tp_base */
 637    0,                                          /* tp_dict */
 638    (descrgetfunc)getset_get,                   /* tp_descr_get */
 639    (descrsetfunc)getset_set,                   /* tp_descr_set */
 640};
 641
 642PyTypeObject PyWrapperDescr_Type = {
 643    PyVarObject_HEAD_INIT(&PyType_Type, 0)
 644    "wrapper_descriptor",
 645    sizeof(PyWrapperDescrObject),
 646    0,
 647    (destructor)descr_dealloc,                  /* tp_dealloc */
 648    0,                                          /* tp_print */
 649    0,                                          /* tp_getattr */
 650    0,                                          /* tp_setattr */
 651    0,                                          /* tp_reserved */
 652    (reprfunc)wrapperdescr_repr,                /* tp_repr */
 653    0,                                          /* tp_as_number */
 654    0,                                          /* tp_as_sequence */
 655    0,                                          /* tp_as_mapping */
 656    0,                                          /* tp_hash */
 657    (ternaryfunc)wrapperdescr_call,             /* tp_call */
 658    0,                                          /* tp_str */
 659    PyObject_GenericGetAttr,                    /* tp_getattro */
 660    0,                                          /* tp_setattro */
 661    0,                                          /* tp_as_buffer */
 662    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
 663    0,                                          /* tp_doc */
 664    descr_traverse,                             /* tp_traverse */
 665    0,                                          /* tp_clear */
 666    0,                                          /* tp_richcompare */
 667    0,                                          /* tp_weaklistoffset */
 668    0,                                          /* tp_iter */
 669    0,                                          /* tp_iternext */
 670    descr_methods,                              /* tp_methods */
 671    descr_members,                              /* tp_members */
 672    wrapperdescr_getset,                        /* tp_getset */
 673    0,                                          /* tp_base */
 674    0,                                          /* tp_dict */
 675    (descrgetfunc)wrapperdescr_get,             /* tp_descr_get */
 676    0,                                          /* tp_descr_set */
 677};
 678
 679static PyDescrObject *
 680descr_new(PyTypeObject *descrtype, PyTypeObject *type, const char *name)
 681{
 682    PyDescrObject *descr;
 683
 684    descr = (PyDescrObject *)PyType_GenericAlloc(descrtype, 0);
 685    if (descr != NULL) {
 686        Py_XINCREF(type);
 687        descr->d_type = type;
 688        descr->d_name = PyUnicode_InternFromString(name);
 689        if (descr->d_name == NULL) {
 690            Py_DECREF(descr);
 691            descr = NULL;
 692        }
 693        else {
 694            descr->d_qualname = NULL;
 695        }
 696    }
 697    return descr;
 698}
 699
 700PyObject *
 701PyDescr_NewMethod(PyTypeObject *type, PyMethodDef *method)
 702{
 703    PyMethodDescrObject *descr;
 704
 705    descr = (PyMethodDescrObject *)descr_new(&PyMethodDescr_Type,
 706                                             type, method->ml_name);
 707    if (descr != NULL)
 708        descr->d_method = method;
 709    return (PyObject *)descr;
 710}
 711
 712PyObject *
 713PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
 714{
 715    PyMethodDescrObject *descr;
 716
 717    descr = (PyMethodDescrObject *)descr_new(&PyClassMethodDescr_Type,
 718                                             type, method->ml_name);
 719    if (descr != NULL)
 720        descr->d_method = method;
 721    return (PyObject *)descr;
 722}
 723
 724PyObject *
 725PyDescr_NewMember(PyTypeObject *type, PyMemberDef *member)
 726{
 727    PyMemberDescrObject *descr;
 728
 729    descr = (PyMemberDescrObject *)descr_new(&PyMemberDescr_Type,
 730                                             type, member->name);
 731    if (descr != NULL)
 732        descr->d_member = member;
 733    return (PyObject *)descr;
 734}
 735
 736PyObject *
 737PyDescr_NewGetSet(PyTypeObject *type, PyGetSetDef *getset)
 738{
 739    PyGetSetDescrObject *descr;
 740
 741    descr = (PyGetSetDescrObject *)descr_new(&PyGetSetDescr_Type,
 742                                             type, getset->name);
 743    if (descr != NULL)
 744        descr->d_getset = getset;
 745    return (PyObject *)descr;
 746}
 747
 748PyObject *
 749PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *base, void *wrapped)
 750{
 751    PyWrapperDescrObject *descr;
 752
 753    descr = (PyWrapperDescrObject *)descr_new(&PyWrapperDescr_Type,
 754                                             type, base->name);
 755    if (descr != NULL) {
 756        descr->d_base = base;
 757        descr->d_wrapped = wrapped;
 758    }
 759    return (PyObject *)descr;
 760}
 761
 762
 763/* --- mappingproxy: read-only proxy for mappings --- */
 764
 765/* This has no reason to be in this file except that adding new files is a
 766   bit of a pain */
 767
 768typedef struct {
 769    PyObject_HEAD
 770    PyObject *mapping;
 771} mappingproxyobject;
 772
 773static Py_ssize_t
 774mappingproxy_len(mappingproxyobject *pp)
 775{
 776    return PyObject_Size(pp->mapping);
 777}
 778
 779static PyObject *
 780mappingproxy_getitem(mappingproxyobject *pp, PyObject *key)
 781{
 782    return PyObject_GetItem(pp->mapping, key);
 783}
 784
 785static PyMappingMethods mappingproxy_as_mapping = {
 786    (lenfunc)mappingproxy_len,                  /* mp_length */
 787    (binaryfunc)mappingproxy_getitem,           /* mp_subscript */
 788    0,                                          /* mp_ass_subscript */
 789};
 790
 791static int
 792mappingproxy_contains(mappingproxyobject *pp, PyObject *key)
 793{
 794    if (PyDict_CheckExact(pp->mapping))
 795        return PyDict_Contains(pp->mapping, key);
 796    else
 797        return PySequence_Contains(pp->mapping, key);
 798}
 799
 800static PySequenceMethods mappingproxy_as_sequence = {
 801    0,                                          /* sq_length */
 802    0,                                          /* sq_concat */
 803    0,                                          /* sq_repeat */
 804    0,                                          /* sq_item */
 805    0,                                          /* sq_slice */
 806    0,                                          /* sq_ass_item */
 807    0,                                          /* sq_ass_slice */
 808    (objobjproc)mappingproxy_contains,                 /* sq_contains */
 809    0,                                          /* sq_inplace_concat */
 810    0,                                          /* sq_inplace_repeat */
 811};
 812
 813static PyObject *
 814mappingproxy_get(mappingproxyobject *pp, PyObject *args)
 815{
 816    PyObject *key, *def = Py_None;
 817    _Py_IDENTIFIER(get);
 818
 819    if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def))
 820        return NULL;
 821    return _PyObject_CallMethodId(pp->mapping, &PyId_get, "(OO)", key, def);
 822}
 823
 824static PyObject *
 825mappingproxy_keys(mappingproxyobject *pp)
 826{
 827    _Py_IDENTIFIER(keys);
 828    return _PyObject_CallMethodId(pp->mapping, &PyId_keys, NULL);
 829}
 830
 831static PyObject *
 832mappingproxy_values(mappingproxyobject *pp)
 833{
 834    _Py_IDENTIFIER(values);
 835    return _PyObject_CallMethodId(pp->mapping, &PyId_values, NULL);
 836}
 837
 838static PyObject *
 839mappingproxy_items(mappingproxyobject *pp)
 840{
 841    _Py_IDENTIFIER(items);
 842    return _PyObject_CallMethodId(pp->mapping, &PyId_items, NULL);
 843}
 844
 845static PyObject *
 846mappingproxy_copy(mappingproxyobject *pp)
 847{
 848    _Py_IDENTIFIER(copy);
 849    return _PyObject_CallMethodId(pp->mapping, &PyId_copy, NULL);
 850}
 851
 852/* WARNING: mappingproxy methods must not give access
 853            to the underlying mapping */
 854
 855static PyMethodDef mappingproxy_methods[] = {
 856    {"get",       (PyCFunction)mappingproxy_get,        METH_VARARGS,
 857     PyDoc_STR("D.get(k[,d]) -> D[k] if k in D, else d."
 858               "  d defaults to None.")},
 859    {"keys",      (PyCFunction)mappingproxy_keys,       METH_NOARGS,
 860     PyDoc_STR("D.keys() -> list of D's keys")},
 861    {"values",    (PyCFunction)mappingproxy_values,     METH_NOARGS,
 862     PyDoc_STR("D.values() -> list of D's values")},
 863    {"items",     (PyCFunction)mappingproxy_items,      METH_NOARGS,
 864     PyDoc_STR("D.items() -> list of D's (key, value) pairs, as 2-tuples")},
 865    {"copy",      (PyCFunction)mappingproxy_copy,       METH_NOARGS,
 866     PyDoc_STR("D.copy() -> a shallow copy of D")},
 867    {0}
 868};
 869
 870static void
 871mappingproxy_dealloc(mappingproxyobject *pp)
 872{
 873    _PyObject_GC_UNTRACK(pp);
 874    Py_DECREF(pp->mapping);
 875    PyObject_GC_Del(pp);
 876}
 877
 878static PyObject *
 879mappingproxy_getiter(mappingproxyobject *pp)
 880{
 881    return PyObject_GetIter(pp->mapping);
 882}
 883
 884static PyObject *
 885mappingproxy_str(mappingproxyobject *pp)
 886{
 887    return PyObject_Str(pp->mapping);
 888}
 889
 890static PyObject *
 891mappingproxy_repr(mappingproxyobject *pp)
 892{
 893    return PyUnicode_FromFormat("mappingproxy(%R)", pp->mapping);
 894}
 895
 896static int
 897mappingproxy_traverse(PyObject *self, visitproc visit, void *arg)
 898{
 899    mappingproxyobject *pp = (mappingproxyobject *)self;
 900    Py_VISIT(pp->mapping);
 901    return 0;
 902}
 903
 904static PyObject *
 905mappingproxy_richcompare(mappingproxyobject *v, PyObject *w, int op)
 906{
 907    return PyObject_RichCompare(v->mapping, w, op);
 908}
 909
 910static int
 911mappingproxy_check_mapping(PyObject *mapping)
 912{
 913    if (!PyMapping_Check(mapping)
 914        || PyList_Check(mapping)
 915        || PyTuple_Check(mapping)) {
 916        PyErr_Format(PyExc_TypeError,
 917                    "mappingproxy() argument must be a mapping, not %s",
 918                    Py_TYPE(mapping)->tp_name);
 919        return -1;
 920    }
 921    return 0;
 922}
 923
 924static PyObject*
 925mappingproxy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 926{
 927    static char *kwlist[] = {"mapping", NULL};
 928    PyObject *mapping;
 929    mappingproxyobject *mappingproxy;
 930
 931    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:mappingproxy",
 932                                     kwlist, &mapping))
 933        return NULL;
 934
 935    if (mappingproxy_check_mapping(mapping) == -1)
 936        return NULL;
 937
 938    mappingproxy = PyObject_GC_New(mappingproxyobject, &PyDictProxy_Type);
 939    if (mappingproxy == NULL)
 940        return NULL;
 941    Py_INCREF(mapping);
 942    mappingproxy->mapping = mapping;
 943    _PyObject_GC_TRACK(mappingproxy);
 944    return (PyObject *)mappingproxy;
 945}
 946
 947PyTypeObject PyDictProxy_Type = {
 948    PyVarObject_HEAD_INIT(&PyType_Type, 0)
 949    "mappingproxy",                             /* tp_name */
 950    sizeof(mappingproxyobject),                 /* tp_basicsize */
 951    0,                                          /* tp_itemsize */
 952    /* methods */
 953    (destructor)mappingproxy_dealloc,           /* tp_dealloc */
 954    0,                                          /* tp_print */
 955    0,                                          /* tp_getattr */
 956    0,                                          /* tp_setattr */
 957    0,                                          /* tp_reserved */
 958    (reprfunc)mappingproxy_repr,                /* tp_repr */
 959    0,                                          /* tp_as_number */
 960    &mappingproxy_as_sequence,                  /* tp_as_sequence */
 961    &mappingproxy_as_mapping,                   /* tp_as_mapping */
 962    0,                                          /* tp_hash */
 963    0,                                          /* tp_call */
 964    (reprfunc)mappingproxy_str,                 /* tp_str */
 965    PyObject_GenericGetAttr,                    /* tp_getattro */
 966    0,                                          /* tp_setattro */
 967    0,                                          /* tp_as_buffer */
 968    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
 969    0,                                          /* tp_doc */
 970    mappingproxy_traverse,                      /* tp_traverse */
 971    0,                                          /* tp_clear */
 972    (richcmpfunc)mappingproxy_richcompare,      /* tp_richcompare */
 973    0,                                          /* tp_weaklistoffset */
 974    (getiterfunc)mappingproxy_getiter,          /* tp_iter */
 975    0,                                          /* tp_iternext */
 976    mappingproxy_methods,                       /* tp_methods */
 977    0,                                          /* tp_members */
 978    0,                                          /* tp_getset */
 979    0,                                          /* tp_base */
 980    0,                                          /* tp_dict */
 981    0,                                          /* tp_descr_get */
 982    0,                                          /* tp_descr_set */
 983    0,                                          /* tp_dictoffset */
 984    0,                                          /* tp_init */
 985    0,                                          /* tp_alloc */
 986    mappingproxy_new,                           /* tp_new */
 987};
 988
 989PyObject *
 990PyDictProxy_New(PyObject *mapping)
 991{
 992    mappingproxyobject *pp;
 993
 994    if (mappingproxy_check_mapping(mapping) == -1)
 995        return NULL;
 996
 997    pp = PyObject_GC_New(mappingproxyobject, &PyDictProxy_Type);
 998    if (pp != NULL) {
 999        Py_INCREF(mapping);
1000        pp->mapping = mapping;
1001        _PyObject_GC_TRACK(pp);
1002    }
1003    return (PyObject *)pp;
1004}
1005
1006
1007/* --- Wrapper object for "slot" methods --- */
1008
1009/* This has no reason to be in this file except that adding new files is a
1010   bit of a pain */
1011
1012typedef struct {
1013    PyObject_HEAD
1014    PyWrapperDescrObject *descr;
1015    PyObject *self;
1016} wrapperobject;
1017
1018#define Wrapper_Check(v) (Py_TYPE(v) == &_PyMethodWrapper_Type)
1019
1020static void
1021wrapper_dealloc(wrapperobject *wp)
1022{
1023    PyObject_GC_UnTrack(wp);
1024    Py_TRASHCAN_SAFE_BEGIN(wp)
1025    Py_XDECREF(wp->descr);
1026    Py_XDECREF(wp->self);
1027    PyObject_GC_Del(wp);
1028    Py_TRASHCAN_SAFE_END(wp)
1029}
1030
1031#define TEST_COND(cond) ((cond) ? Py_True : Py_False)
1032
1033static PyObject *
1034wrapper_richcompare(PyObject *a, PyObject *b, int op)
1035{
1036    Py_intptr_t result;
1037    PyObject *v;
1038    PyWrapperDescrObject *a_descr, *b_descr;
1039
1040    assert(a != NULL && b != NULL);
1041
1042    /* both arguments should be wrapperobjects */
1043    if (!Wrapper_Check(a) || !Wrapper_Check(b)) {
1044        v = Py_NotImplemented;
1045        Py_INCREF(v);
1046        return v;
1047    }
1048
1049    /* compare by descriptor address; if the descriptors are the same,
1050       compare by the objects they're bound to */
1051    a_descr = ((wrapperobject *)a)->descr;
1052    b_descr = ((wrapperobject *)b)->descr;
1053    if (a_descr == b_descr) {
1054        a = ((wrapperobject *)a)->self;
1055        b = ((wrapperobject *)b)->self;
1056        return PyObject_RichCompare(a, b, op);
1057    }
1058
1059    result = a_descr - b_descr;
1060    switch (op) {
1061    case Py_EQ:
1062        v = TEST_COND(result == 0);
1063        break;
1064    case Py_NE:
1065        v = TEST_COND(result != 0);
1066        break;
1067    case Py_LE:
1068        v = TEST_COND(result <= 0);
1069        break;
1070    case Py_GE:
1071        v = TEST_COND(result >= 0);
1072        break;
1073    case Py_LT:
1074        v = TEST_COND(result < 0);
1075        break;
1076    case Py_GT:
1077        v = TEST_COND(result > 0);
1078        break;
1079    default:
1080        PyErr_BadArgument();
1081        return NULL;
1082    }
1083    Py_INCREF(v);
1084    return v;
1085}
1086
1087static Py_hash_t
1088wrapper_hash(wrapperobject *wp)
1089{
1090    Py_hash_t x, y;
1091    x = _Py_HashPointer(wp->descr);
1092    if (x == -1)
1093        return -1;
1094    y = PyObject_Hash(wp->self);
1095    if (y == -1)
1096        return -1;
1097    x = x ^ y;
1098    if (x == -1)
1099        x = -2;
1100    return x;
1101}
1102
1103static PyObject *
1104wrapper_repr(wrapperobject *wp)
1105{
1106    return PyUnicode_FromFormat("<method-wrapper '%s' of %s object at %p>",
1107                               wp->descr->d_base->name,
1108                               wp->self->ob_type->tp_name,
1109                               wp->self);
1110}
1111
1112static PyObject *
1113wrapper_reduce(wrapperobject *wp)
1114{
1115    PyObject *builtins;
1116    PyObject *getattr;
1117    _Py_IDENTIFIER(getattr);
1118
1119    builtins = PyEval_GetBuiltins();
1120    getattr = _PyDict_GetItemId(builtins, &PyId_getattr);
1121    return Py_BuildValue("O(OO)", getattr, wp->self, PyDescr_NAME(wp->descr));
1122}
1123
1124static PyMethodDef wrapper_methods[] = {
1125    {"__reduce__", (PyCFunction)wrapper_reduce, METH_NOARGS, NULL},
1126    {NULL, NULL}
1127};
1128
1129static PyMemberDef wrapper_members[] = {
1130    {"__self__", T_OBJECT, offsetof(wrapperobject, self), READONLY},
1131    {0}
1132};
1133
1134static PyObject *
1135wrapper_objclass(wrapperobject *wp)
1136{
1137    PyObject *c = (PyObject *)PyDescr_TYPE(wp->descr);
1138
1139    Py_INCREF(c);
1140    return c;
1141}
1142
1143static PyObject *
1144wrapper_name(wrapperobject *wp)
1145{
1146    const char *s = wp->descr->d_base->name;
1147
1148    return PyUnicode_FromString(s);
1149}
1150
1151static PyObject *
1152wrapper_doc(wrapperobject *wp, void *closure)
1153{
1154    return _PyType_GetDocFromInternalDoc(wp->descr->d_base->name, wp->descr->d_base->doc);
1155}
1156
1157static PyObject *
1158wrapper_text_signature(wrapperobject *wp, void *closure)
1159{
1160    return _PyType_GetTextSignatureFromInternalDoc(wp->descr->d_base->name, wp->descr->d_base->doc);
1161}
1162
1163static PyObject *
1164wrapper_qualname(wrapperobject *wp)
1165{
1166    return descr_get_qualname((PyDescrObject *)wp->descr);
1167}
1168
1169static PyGetSetDef wrapper_getsets[] = {
1170    {"__objclass__", (getter)wrapper_objclass},
1171    {"__name__", (getter)wrapper_name},
1172    {"__qualname__", (getter)wrapper_qualname},
1173    {"__doc__", (getter)wrapper_doc},
1174    {"__text_signature__", (getter)wrapper_text_signature},
1175    {0}
1176};
1177
1178static PyObject *
1179wrapper_call(wrapperobject *wp, PyObject *args, PyObject *kwds)
1180{
1181    wrapperfunc wrapper = wp->descr->d_base->wrapper;
1182    PyObject *self = wp->self;
1183
1184    if (wp->descr->d_base->flags & PyWrapperFlag_KEYWORDS) {
1185        wrapperfunc_kwds wk = (wrapperfunc_kwds)wrapper;
1186        return (*wk)(self, args, wp->descr->d_wrapped, kwds);
1187    }
1188
1189    if (kwds != NULL && (!PyDict_Check(kwds) || PyDict_Size(kwds) != 0)) {
1190        PyErr_Format(PyExc_TypeError,
1191                     "wrapper %s doesn't take keyword arguments",
1192                     wp->descr->d_base->name);
1193        return NULL;
1194    }
1195    return (*wrapper)(self, args, wp->descr->d_wrapped);
1196}
1197
1198static int
1199wrapper_traverse(PyObject *self, visitproc visit, void *arg)
1200{
1201    wrapperobject *wp = (wrapperobject *)self;
1202    Py_VISIT(wp->descr);
1203    Py_VISIT(wp->self);
1204    return 0;
1205}
1206
1207PyTypeObject _PyMethodWrapper_Type = {
1208    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1209    "method-wrapper",                           /* tp_name */
1210    sizeof(wrapperobject),                      /* tp_basicsize */
1211    0,                                          /* tp_itemsize */
1212    /* methods */
1213    (destructor)wrapper_dealloc,                /* tp_dealloc */
1214    0,                                          /* tp_print */
1215    0,                                          /* tp_getattr */
1216    0,                                          /* tp_setattr */
1217    0,                                          /* tp_reserved */
1218    (reprfunc)wrapper_repr,                     /* tp_repr */
1219    0,                                          /* tp_as_number */
1220    0,                                          /* tp_as_sequence */
1221    0,                                          /* tp_as_mapping */
1222    (hashfunc)wrapper_hash,                     /* tp_hash */
1223    (ternaryfunc)wrapper_call,                  /* tp_call */
1224    0,                                          /* tp_str */
1225    PyObject_GenericGetAttr,                    /* tp_getattro */
1226    0,                                          /* tp_setattro */
1227    0,                                          /* tp_as_buffer */
1228    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1229    0,                                          /* tp_doc */
1230    wrapper_traverse,                           /* tp_traverse */
1231    0,                                          /* tp_clear */
1232    wrapper_richcompare,                        /* tp_richcompare */
1233    0,                                          /* tp_weaklistoffset */
1234    0,                                          /* tp_iter */
1235    0,                                          /* tp_iternext */
1236    wrapper_methods,                            /* tp_methods */
1237    wrapper_members,                            /* tp_members */
1238    wrapper_getsets,                            /* tp_getset */
1239    0,                                          /* tp_base */
1240    0,                                          /* tp_dict */
1241    0,                                          /* tp_descr_get */
1242    0,                                          /* tp_descr_set */
1243};
1244
1245PyObject *
1246PyWrapper_New(PyObject *d, PyObject *self)
1247{
1248    wrapperobject *wp;
1249    PyWrapperDescrObject *descr;
1250
1251    assert(PyObject_TypeCheck(d, &PyWrapperDescr_Type));
1252    descr = (PyWrapperDescrObject *)d;
1253    assert(_PyObject_RealIsSubclass((PyObject *)Py_TYPE(self),
1254                                    (PyObject *)PyDescr_TYPE(descr)));
1255
1256    wp = PyObject_GC_New(wrapperobject, &_PyMethodWrapper_Type);
1257    if (wp != NULL) {
1258        Py_INCREF(descr);
1259        wp->descr = descr;
1260        Py_INCREF(self);
1261        wp->self = self;
1262        _PyObject_GC_TRACK(wp);
1263    }
1264    return (PyObject *)wp;
1265}
1266
1267
1268/* A built-in 'property' type */
1269
1270/*
1271class property(object):
1272
1273    def __init__(self, fget=None, fset=None, fdel=None, doc=None):
1274        if doc is None and fget is not None and hasattr(fget, "__doc__"):
1275            doc = fget.__doc__
1276        self.__get = fget
1277        self.__set = fset
1278        self.__del = fdel
1279        self.__doc__ = doc
1280
1281    def __get__(self, inst, type=None):
1282        if inst is None:
1283            return self
1284        if self.__get is None:
1285            raise AttributeError, "unreadable attribute"
1286        return self.__get(inst)
1287
1288    def __set__(self, inst, value):
1289        if self.__set is None:
1290            raise AttributeError, "can't set attribute"
1291        return self.__set(inst, value)
1292
1293    def __delete__(self, inst):
1294        if self.__del is None:
1295            raise AttributeError, "can't delete attribute"
1296        return self.__del(inst)
1297
1298*/
1299
1300typedef struct {
1301    PyObject_HEAD
1302    PyObject *prop_get;
1303    PyObject *prop_set;
1304    PyObject *prop_del;
1305    PyObject *prop_doc;
1306    int getter_doc;
1307} propertyobject;
1308
1309static PyObject * property_copy(PyObject *, PyObject *, PyObject *,
1310                                  PyObject *);
1311
1312static PyMemberDef property_members[] = {
1313    {"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY},
1314    {"fset", T_OBJECT, offsetof(propertyobject, prop_set), READONLY},
1315    {"fdel", T_OBJECT, offsetof(propertyobject, prop_del), READONLY},
1316    {"__doc__",  T_OBJECT, offsetof(propertyobject, prop_doc), 0},
1317    {0}
1318};
1319
1320
1321PyDoc_STRVAR(getter_doc,
1322             "Descriptor to change the getter on a property.");
1323
1324static PyObject *
1325property_getter(PyObject *self, PyObject *getter)
1326{
1327    return property_copy(self, getter, NULL, NULL);
1328}
1329
1330
1331PyDoc_STRVAR(setter_doc,
1332             "Descriptor to change the setter on a property.");
1333
1334static PyObject *
1335property_setter(PyObject *self, PyObject *setter)
1336{
1337    return property_copy(self, NULL, setter, NULL);
1338}
1339
1340
1341PyDoc_STRVAR(deleter_doc,
1342             "Descriptor to change the deleter on a property.");
1343
1344static PyObject *
1345property_deleter(PyObject *self, PyObject *deleter)
1346{
1347    return property_copy(self, NULL, NULL, deleter);
1348}
1349
1350
1351static PyMethodDef property_methods[] = {
1352    {"getter", property_getter, METH_O, getter_doc},
1353    {"setter", property_setter, METH_O, setter_doc},
1354    {"deleter", property_deleter, METH_O, deleter_doc},
1355    {0}
1356};
1357
1358
1359static void
1360property_dealloc(PyObject *self)
1361{
1362    propertyobject *gs = (propertyobject *)self;
1363
1364    _PyObject_GC_UNTRACK(self);
1365    Py_XDECREF(gs->prop_get);
1366    Py_XDECREF(gs->prop_set);
1367    Py_XDECREF(gs->prop_del);
1368    Py_XDECREF(gs->prop_doc);
1369    self->ob_type->tp_free(self);
1370}
1371
1372static PyObject *
1373property_descr_get(PyObject *self, PyObject *obj, PyObject *type)
1374{
1375    static PyObject * volatile cached_args = NULL;
1376    PyObject *args;
1377    PyObject *ret;
1378    propertyobject *gs = (propertyobject *)self;
1379
1380    if (obj == NULL || obj == Py_None) {
1381        Py_INCREF(self);
1382        return self;
1383    }
1384    if (gs->prop_get == NULL) {
1385        PyErr_SetString(PyExc_AttributeError, "unreadable attribute");
1386        return NULL;
1387    }
1388    args = cached_args;
1389    cached_args = NULL;
1390    if (!args) {
1391        args = PyTuple_New(1);
1392        if (!args)
1393            return NULL;
1394        _PyObject_GC_UNTRACK(args);
1395    }
1396    Py_INCREF(obj);
1397    PyTuple_SET_ITEM(args, 0, obj);
1398    ret = PyObject_Call(gs->prop_get, args, NULL);
1399    if (cached_args == NULL && Py_REFCNT(args) == 1) {
1400        assert(Py_SIZE(args) == 1);
1401        assert(PyTuple_GET_ITEM(args, 0) == obj);
1402        cached_args = args;
1403        Py_DECREF(obj);
1404    }
1405    else {
1406        assert(Py_REFCNT(args) >= 1);
1407        _PyObject_GC_TRACK(args);
1408        Py_DECREF(args);
1409    }
1410    return ret;
1411}
1412
1413static int
1414property_descr_set(PyObject *self, PyObject *obj, PyObject *value)
1415{
1416    propertyobject *gs = (propertyobject *)self;
1417    PyObject *func, *res;
1418
1419    if (value == NULL)
1420        func = gs->prop_del;
1421    else
1422        func = gs->prop_set;
1423    if (func == NULL) {
1424        PyErr_SetString(PyExc_AttributeError,
1425                        value == NULL ?
1426                        "can't delete attribute" :
1427                "can't set attribute");
1428        return -1;
1429    }
1430    if (value == NULL)
1431        res = PyObject_CallFunctionObjArgs(func, obj, NULL);
1432    else
1433        res = PyObject_CallFunctionObjArgs(func, obj, value, NULL);
1434    if (res == NULL)
1435        return -1;
1436    Py_DECREF(res);
1437    return 0;
1438}
1439
1440static PyObject *
1441property_copy(PyObject *old, PyObject *get, PyObject *set, PyObject *del)
1442{
1443    propertyobject *pold = (propertyobject *)old;
1444    PyObject *new, *type, *doc;
1445
1446    type = PyObject_Type(old);
1447    if (type == NULL)
1448        return NULL;
1449
1450    if (get == NULL || get == Py_None) {
1451        Py_XDECREF(get);
1452        get = pold->prop_get ? pold->prop_get : Py_None;
1453    }
1454    if (set == NULL || set == Py_None) {
1455        Py_XDECREF(set);
1456        set = pold->prop_set ? pold->prop_set : Py_None;
1457    }
1458    if (del == NULL || del == Py_None) {
1459        Py_XDECREF(del);
1460        del = pold->prop_del ? pold->prop_del : Py_None;
1461    }
1462    if (pold->getter_doc && get != Py_None) {
1463        /* make _init use __doc__ from getter */
1464        doc = Py_None;
1465    }
1466    else {
1467        doc = pold->prop_doc ? pold->prop_doc : Py_None;
1468    }
1469
1470    new =  PyObject_CallFunction(type, "OOOO", get, set, del, doc);
1471    Py_DECREF(type);
1472    if (new == NULL)
1473        return NULL;
1474    return new;
1475}
1476
1477static int
1478property_init(PyObject *self, PyObject *args, PyObject *kwds)
1479{
1480    PyObject *get = NULL, *set = NULL, *del = NULL, *doc = NULL;
1481    static char *kwlist[] = {"fget", "fset", "fdel", "doc", 0};
1482    propertyobject *prop = (propertyobject *)self;
1483
1484    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO:property",
1485                                     kwlist, &get, &set, &del, &doc))
1486        return -1;
1487
1488    if (get == Py_None)
1489        get = NULL;
1490    if (set == Py_None)
1491        set = NULL;
1492    if (del == Py_None)
1493        del = NULL;
1494
1495    Py_XINCREF(get);
1496    Py_XINCREF(set);
1497    Py_XINCREF(del);
1498    Py_XINCREF(doc);
1499
1500    prop->prop_get = get;
1501    prop->prop_set = set;
1502    prop->prop_del = del;
1503    prop->prop_doc = doc;
1504    prop->getter_doc = 0;
1505
1506    /* if no docstring given and the getter has one, use that one */
1507    if ((doc == NULL || doc == Py_None) && get != NULL) {
1508        _Py_IDENTIFIER(__doc__);
1509        PyObject *get_doc = _PyObject_GetAttrId(get, &PyId___doc__);
1510        if (get_doc) {
1511            if (Py_TYPE(self) == &PyProperty_Type) {
1512                Py_XSETREF(prop->prop_doc, get_doc);
1513            }
1514

Large files files are truncated, but you can click here to view the full file