Re: getattr()

Guido.van.Rossum@cwi.nl
Mon, 07 Mar 1994 23:22:23 +0100

> I am told that getattr() is the appropriate and fast way of getting
> attributes of a class instance from within a C program. Since this
> functions always returns an object * type it follows that if the
> attribute is a simple string it is necessary to use getargs() to
> extract the string from the object returned by getattr(), or is
> there some other recommended method for getting the string value?

No, getargs() is a convenience function. You never *need* to call it
-- it's just less code and less thinking in most cases. Have a look
at example code anywhere in the built-in modules.

What you want to do to extract a string without using getattr() is
something like

object *attr = getattr(obj, "some_attribute");
char *str;
int len;
/* Obligatory error check: */
if (attr == NULL)
return NULL; /* Caller will see exception from getattr() */
if (!is_stringobject(attr)) {
DECREF(attr); /* Don't cause memory leak! */
err_setstr(TypeError, "string expected");
return NULL;
}
str = getstringvalue(attr);
len = getstringsize(attr);
<do whatever you want with str>
DECREF(attr);
/* Return a valid object, e.g. None */
INCREF(None);
return None;

> Is this also required if the attribute returned is a complex object
> such as a list object?

Similar, just is is_listobject() and then access the list's items with
getlistitem() and getlistsize() etc.

> My specific question is, is it necessary to use getargs() with a
> format string of "O" to extract a list object from a value returned
> by getattr() or is the value returned sufficient for use in
> functions such as addlistitem()?

No, getargs(obj, "O", &val) only checks that obj is non-NULL and
INCREF's it, then copies its address into val. Note that even here
you have to check that it's really a list -- getlistitem() may dump
core (if not now then in a future release) when applied to a non-list
object. (I can easily imagine an extension of getargs() with "L", "T"
format characters and so on for the most common object types, but for
now you'll have to do with "O" and "S".)

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
URL: <http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>