Re: getattr()

Andy Bensky (ab@infoseek.com)
Thu, 17 Mar 1994 16:22:13 +0800

Some time ago Guido indicated that this is the correct way to extract
a string attribute from an object instance in a C function:
> 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;
>

I am concerened about the persistence of 'str'. Is it safe to return this
pointer back to a caller, assuming it is understood that it is readonly.
Would it be necessary to delay the DECREF(attr) until after the string is
no longer needed? If that is the case then it might be necessary to make
a local copy and return that.

The question is, if a char * is extracted from a string object using
getstringvalue() will it be freed when the object is garbage collected.
My guess is yes, but I wanted to confirm this.

Thanks again,

andy bensky
infoseek corp.