Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Lib/test/test_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,19 @@ def __delattr__(self, *args):
del testme.cardinal
self.assertCallStack([('__delattr__', (testme, "cardinal"))])

def testHasAttrString(self):

from test.support import import_helper
_testcapi = import_helper.import_module('_testcapi')

class A:
def __init__(self):
self.attr = 1

a = A()
self.assertEqual(_testcapi.hasattr_string(a, "attr"), True)
self.assertEqual(_testcapi.hasattr_string(a, "noattr"), False)

def testDel(self):
x = []

Expand Down
24 changes: 24 additions & 0 deletions Modules/_testcapimodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -4846,6 +4846,29 @@ sequence_setitem(PyObject *self, PyObject *args)
}


static PyObject *
hasattr_string(PyObject *self, PyObject* args)
{
PyObject* obj;
PyObject* attr_name;

if(!PyArg_UnpackTuple(args, "hasattr_string", 2, 2, &obj, &attr_name))
return NULL;

if(!PyUnicode_Check(attr_name))
{
PyErr_SetString(PyExc_TypeError, "attribute name must a be string");
return PyErr_Occurred();
}

const char *name_str = PyUnicode_AsUTF8(attr_name);
if(PyObject_HasAttrString(obj, name_str))
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}


/* Functions for testing C calling conventions (METH_*) are named meth_*,
* e.g. "meth_varargs" for METH_VARARGS.
*
Expand Down Expand Up @@ -5705,6 +5728,7 @@ static PyMethodDef TestMethods[] = {
{"write_unraisable_exc", test_write_unraisable_exc, METH_VARARGS},
{"sequence_getitem", sequence_getitem, METH_VARARGS},
{"sequence_setitem", sequence_setitem, METH_VARARGS},
{"hasattr_string", hasattr_string, METH_VARARGS},
{"meth_varargs", meth_varargs, METH_VARARGS},
{"meth_varargs_keywords", _PyCFunction_CAST(meth_varargs_keywords), METH_VARARGS|METH_KEYWORDS},
{"meth_o", meth_o, METH_O},
Expand Down