C-API, tp_dictoffset vs tp_members
"Martin v. Löwis"
martin at v.loewis.de
Sun Jul 26 04:04:12 EDT 2009
> When would I use PyObject_SetAttrString/tp_dictoffset instead of tp_members?
When I have a variable list of attributes, and cannot statically know
what those attributes might be.
> I have a predefined set of members, some of which are optional.
Having optional fields is also a good reason.
> The problem
> I had with an embedded dictionary was that I can't see its elements using
> "dir()".
How so? That should work fine.
> Now I just converted to using tp_members, and it still seems to
> work correctly for the cases I tested.
So how do you do optional fields now? In particular, how would you do
optional integers?
> Even better, I can declare the fields
> as read-only then and add doc-strings. So, I wonder, what made the original
> author[2] use tp_dictoffset instead?
Most likely, it was the simplest approach. This code only wants to set
the attributes, and never read them. It's easier to maintain: if you
want to add a field with tp_members, you have to change multiple places,
and you have to consider garbage collection (assuming you have embedded
objects). With tp_dictoffset, adding another attribute is easy.
Regards,
Martin
More information about the Python-list
mailing list