[Python-Dev] PyObject_SetAttr - is it the only way types should set attributes?

Guido van Rossum guido@python.org
Wed, 15 Aug 2001 14:10:58 -0400

>     >> I'm also curious about the new type-class unification stuff.  Is it
>     >> possible to modify a C object via something like a C struct and have
>     >> that change be visible as a modified attrbute at the Python level?
>     Guido> Can you clarify this question?  I feel I should be qualified to
>     Guido> answer this but I don't understand the question...  Maybe an
>     Guido> example would help?

> I'll try to channel Jeremy.  Even if I fail, I think the problem I describe
> is worth noting for PEP 0266.
> Suppose I have an extension module that declares a new type containing a
> "foo" slot in the C struct for the type.  If I implement a method named
> "bar", it's obviously free to modify any of the contents in the struct in
> any way it sees fit.  Now, suppose I also have a getattrfunc that will
> return the contents of the "foo" slot when asked to.  There needs not be any
> setattrfunc or setattrofunc, yet the value in this slot has to be tracked if
> it might be accessed by a programmer.
> I suspect this is just one more place a C extension programmer can blow a
> gaping hole in his foot, but I worry that there's no obvious way to alert
> the programmer to such breakage if/when they upgrade to a version of Python
> that tracks globals.  Seems like a source of very subtle bugs.

Under the new system, the recommended way to make "foo" an attribute
of the object is to have an attribute descriptor named foo in the
type's __dict__.  This descriptor is most likely created when the type
was initialized from the tp_members or tp_getset fields in the type
object.  (I've checked in an example to Modules/xxsubtype.c -- do a
cvs update and look for "struct memberlist".)

I suppose the globals-tracking mechanism could have enough smarts to
look in the type's __dict__ for attribute descriptors; if it finds
certain types of descriptors it should assume that these can be
changed at any time.

--Guido van Rossum (home page: http://www.python.org/~guido/)