object() can't have attributes

Zachary Ware zachary.ware+pylist at gmail.com
Wed Dec 23 11:17:09 EST 2015


On Dec 23, 2015 7:00 AM, "Chris Angelico" <rosuav at gmail.com> wrote:
> On Wed, Dec 23, 2015 at 11:46 PM, Neal Becker <ndbecker2 at gmail.com> wrote:
> > Sometimes I want to collect attributes on an object.  Usually I would make
> > an empty class for this.  But it seems unnecessarily verbose to do this.  So
> > I thought, why not just use an Object?  But no, an instance of Object
> > apparantly can't have an attribute.  Is this intentional?
>
> Yes; there are other uses of object() that benefit from being
> extremely compact. You can use types.SimpleNamespace for this job, or
> you can create the empty class as you're describing. (Chances are you
> can give the class a meaningful name anyway.)

Its more that if you give object() an instance dict, all objects
inheriting from object (i.e., all of them) must have an instance dict,
which would make __slots__ and its benefits impossible.

Another cross-version option:

   >>> bag = type("AttrBag", (), {})()
   >>> bag.spam = 2
   >>> bag.spam
   2

You can even sneak in keyword arguments like SimpleNamespace supports
by passing them in the namespace dict (the third argument):

   >>> bag = type("AttrBag", (), dict(spam=3))()
   >>> bag.spam
   3

Of course, using this you lose easy access to the 'AttrBag' class, but
in most cases you shouldn't need it.  If you do, just make it a
regular class as has been suggested, or save off a reference to the
class before instantiating.

No comments on how ugly this is, though :)

-- 
Zach



More information about the Python-list mailing list