An empty object with dynamic attributes (expando)

Alf P. Steinbach alfps at start.no
Fri Jun 4 22:25:14 EDT 2010


* Terry Reedy, on 05.06.2010 03:01:
> On 6/4/2010 8:01 PM, dmtr wrote:
>>> Why does it have to be a one-liner? Is the Enter key on your keyboard
>>> broken?
>>
>> Nah. I was simply looking for something natural and intuitive, like: m
>> = object(); m.a = 1;
>> Usually python is pretty good providing these natural and intuitive
>> solutions.
>
> As far as I can think of now, one cannot add attributes to *any*
> builtin-class instance, but can add attributes to any user class which
> does not have them disabled.
>
>  >>> [].a = 3
> Traceback (most recent call last):
> File "<pyshell#15>", line 1, in <module>
> [].a = 3
> AttributeError: 'list' object has no attribute 'a'
>  >>> class L(list): pass
>
>  >>> i = L(); i; i.a = 3; i.a
> []
> 3
>
> Terry Jan Reedy

You can add attributes to functions.

I'm not sure, but I think it was you who once provided me with a reference to 
the relevant PEP (thanks!), so I guess it just slipped your mind on a late 
Friday night. :-)

See my earlier reply in this thread regarding that.

Regarding user defined classes, I gather that by "have them [attributes] 
disabled" you're including the case of a class with slots?

There was an article recently in DDJ where the author seemed to be unaware of 
this, but I'm not going to pay for the privilege of commenting on articles.


Cheers & hth.,

- Alf


PS: How come that when I post a blog entry proving mathematically that the 
reader is really really smart, the number of views dropped like a stone? Huh. 
But OK, it was just a late-night posting, I couldn't sleep so I posted a bit of 
what I, late at night, thought was some funny or at least amusing philosophy...

-- 
blog at <url: http://alfps.wordpress.com>



More information about the Python-list mailing list