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>