[capi-sig] Modify tp_getset or PyGetSetDef entries in run-time

Campbell Barton ideasman42 at gmail.com
Fri Jul 6 14:35:29 CEST 2012


While this isnt impossible - its definetly not intended, when python
runs PyType_Ready() it converts the PyGetSetDef's into PyObject's
attribute descriptors which are stored in the PyType's dictionary.
so strongly advice against trying to manipulate that data at low
level... some alternatives could be....

- define pygetattro and manage the lookups on each call - typical way
to handle such cases.
- you could look at assigning properties to a class as can be done in python...

MyClass.foo = property(getx, setx, delx, "This is a property")

... doing in C will be more verbose of course but it should work fine.

On Thu, Jul 5, 2012 at 1:42 PM, Mateusz Loskot <mateusz at loskot.net> wrote:
> Hi,
>
> I have a type object implemented using plain Python 3 C API.
> The type has number of attributes - tp_getset slot set with typical
> table of geters and seters.
> I'd like to find out best way to make certain attributes read-only at run-time.
>
> The table I assign to tp_getset looks like this:
>
> PyGetSetDef Foo_getseters[] =
> {
>     {"text", (getter)Foo_get_text, (setter)Foo_set_text,
> PyDoc_STR("Foo text"), NULL },
>     {NULL}
> };
>
> Now, at some point at run-time, I'd like to disallow assignment to
> .text property
> Obvious way to do that is to check desired condition in Foo_set_text()
> and set AttributeError.
>
> I wonder if it would be possible and sensible to modify the tp_getset slot and
> simply set the Foo_set_text entry in Foo_getseters to NULL.
>
> Is it possible?
> Is there any better way to make an attribute read-only at run-time?
>
> Best regards,
> --
> Mateusz Loskot, http://mateusz.loskot.net
> _______________________________________________
> capi-sig mailing list
> capi-sig at python.org
> http://mail.python.org/mailman/listinfo/capi-sig



-- 
- Campbell


More information about the capi-sig mailing list