Best way to string compare a python object in a getattrofunc?

Cayce Ullman Cayce at actzero.com
Wed Feb 28 17:41:21 EST 2001


Hi,  I'm writing an extension class that has a getattro method implemented
in C.  The method takes a python object as it's name, not a string.  My
question is what is the best way to do this.  For example, if I always want
my extension class to return "eggs" when attribute "spam" is requested, no
matter what is in the instance dictionary, what's the fastest way to compare
the python string object with my string constant.  Currently I'm doing it
this way:

static PyObject *
myec_getattro(myec_object *self, PyObject *name)
{
    if (strcmp(PyString_AsString(name),"spam")==0)
    {
        return PyString_FromString("eggs");
    }

    return Py_FindAttr((PyObject *)self, name);
}

This obviously requires that the every time an attribute is requested it is
converted into a char* then strcmped (obviously some type checking would
eventually be appropriate here).  This seems like a lot of work.  I am
thinking about interning the string "spam" on module initialization, then
saving that pointer somewhere, and then just comparing the pointers on every
fetch.  This approach would save me type checking, string convertion, and a
strcmp.  However, I think it might not be fool proof.  Ie, if someone
computed the attribute name "sp" + "am", this would no longer work (I don't
think that is very likely, though).  Also, if the attribute name came from
some other C module, it seems like that too could have problems.  I can't be
the first person wondering about this, is there a universally accepted best
practice here?

TIA,

Cayce




More information about the Python-list mailing list