Can we create an_object = object() and add attribute like for a class?

Alex Martelli aleaxit at yahoo.com
Sat Apr 29 18:23:45 EDT 2006


Pierre Rouleau <prouleau at impathnetworks.com> wrote:

> Hi all,
> 
> Is there any reason that under Python you cannot instantiate the object
> class and create any attributes like you would be able for a normal class?

Yep: instances of type object do not have a __dict__ and therefore there
is no place to put any attributes.  This is necessary to allow ANY
subclass of object, and thus any type whatsoever, to lack a per-instance
__dict__ (and thus to save its per-instance memory costs), since by the
principle of inheritance (known as Liskov substutition, or also as the
"IS-A" rule) a subclass cannot _remove_ superclass attributes, so if the
universal superclass had a __dict__ so would every type in Python.

> Being able to do it would seem a natural way of declaring namespaces.

I find that ns = type('somename', (), dict(anattribute=23)) isn't too
bad to make a namespace ns, though it has some undesirable issues (e.g.,
ns is implicitly callable, which may make little sense for a namespace).

At any rate, any natural way of declaring a namespace SHOULD allow
arbitrary named arguments in the instantiation call -- bending
principles to give each instance of object a __dict__ would still not
fix that, so that wouldn't do much. I think it's worth the minor bother
to write out something like

class Namespace(object):
    def __init__(self, **kwds): self.__dict__ = kwds

and I generally go further anyway, by defining at least a repr that
shows the attributes' names and values (very useful for debugging...).


Alex



More information about the Python-list mailing list