2006-07-04
A surprise with using object()
instances
A while back I wrote about emulating C structs in Python using (instance) objects to create namespaces, and wrote:
(Avoid the temptation to just use '
ms = object()
', because it hurts your ability to tell different types of structs apart via introspection.)
It turns out that there is another reason to avoid this: it doesn't
work. Somewhat to my surprise, instances of object()
can't have new
attributes put on them. (Instances of Python subclasses of object()
can.)
While I suspect that the behavior is deliberate, there's nothing in
the CPython source code that singles out instances of object()
for
this. As far as I can tell, you can't set attributes on them mostly
because they don't get any sort of attribute storage set up, such as
an instance dictionary.
This does beg the question of what instances of object()
are good for.
As far as I can see the answer is pretty much 'creating minimal sized
unique things as sentinel values', as I did in DefaultArgumentsTrick.
(Tracing through CPython source code out of curiosity is something I do every so often. It teaches me more about how CPython is put together, and it keeps me used to tracing how stuff flows through code I don't know (which is a quite useful skill to have).)