Skip to content

Instantly share code, notes, and snippets.

@methane
Created January 15, 2018 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save methane/4adf85086798c2c2a8ee59181474fb29 to your computer and use it in GitHub Desktop.
Save methane/4adf85086798c2c2a8ee59181474fb29 to your computer and use it in GitHub Desktop.
static PyObject *
getattr_impl(PyObject *v, PyObject *name, int suppress)
{
PyTypeObject *tp = Py_TYPE(v);
PyObject *ret = NULL;
if (!PyUnicode_Check(name)) {
PyErr_Format(PyExc_TypeError,
"attribute name must be string, not '%.200s'",
name->ob_type->tp_name);
return NULL;
}
if (tp->tp_getattro != NULL) {
if (tp->tp_getattro == PyObject_GenericGetAttr) {
ret = _PyObject_GenericGetAttrWithDict(v, name, NULL, suppress);
}
else {
ret = (*tp->tp_getattro)(v, name);
}
}
else if (tp->tp_getattr != NULL) {
const char *name_str = PyUnicode_AsUTF8(name);
if (name_str == NULL)
return NULL;
ret = (*tp->tp_getattr)(v, (char *)name_str);
}
else if (!suppress) {
PyErr_Format(PyExc_AttributeError,
"'%.50s' object has no attribute '%U'",
tp->tp_name, name);
}
if (ret == NULL && suppress &&
PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyErr_Clear();
}
return ret;
}
PyObject *
PyObject_GetAttr(PyObject *v, PyObject *name)
{
return getattr_impl(v, name, 0);
}
PyObject *
_PyObject_GetAttrWithoutError(PyObject *v, PyObject *name)
{
return getattr_impl(v, name, 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment