From: dmtr on
How can I create an empty object with dynamic attributes? It should be
something like:

>>> m = object()
>>> m.myattr = 1

But this doesn't work. And I have to resort to:

>>> class expando(object): pass
>>> m = expando()
>>> m.myattr = 1

Is there a one-liner that would do the thing?

-- Cheers, Dmitry
From: Alf P. Steinbach on
* dmtr, on 03.06.2010 23:00:
> How can I create an empty object with dynamic attributes? It should be
> something like:
>
>>>> m = object()
>>>> m.myattr = 1
>
> But this doesn't work. And I have to resort to:
>
>>>> class expando(object): pass
>>>> m = expando()
>>>> m.myattr = 1
>
> Is there a one-liner that would do the thing?

<example>
>>> m = lambda:0
>>> m.myattr = 1
>>> m.myattr
1
>>> _
</example>

But I feel that that is an abuse of the language, and that an Expando class like
you show is far better.

Thanks for the class name suggestion, by the way -- I've wondered what to call
such a class, and now it's clear. :-)


Cheers & hth.,

- Alf

--
blog at <url: http://alfps.wordpress.com>
From: Steven D'Aprano on
On Thu, 03 Jun 2010 14:00:11 -0700, dmtr wrote:

> How can I create an empty object with dynamic attributes? It should be
> something like:
>
>>>> m = object()
>>>> m.myattr = 1
>
> But this doesn't work. And I have to resort to:
>
>>>> class expando(object): pass
>>>> m = expando()
>>>> m.myattr = 1
>
> Is there a one-liner that would do the thing?

Why does it have to be a one-liner? Is the Enter key on your keyboard
broken?

You have a perfectly good solution: define a class, then instantiate it.
But if you need a one-liner (perhaps to win a game of code golf), then
this will work:

>>> m = type('', (), {})()
>>> m.attribute = 2
>>>



--
Steven
From: dmtr on
> 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.


> You have a perfectly good solution: define a class, then instantiate it.
> But if you need a one-liner (perhaps to win a game of code golf), then
> this will work:
>
> >>> m = type('', (), {})()
> >>> m.attribute = 2

Heh. Creating it dynamically. Ace. ;)

-- Cheers, Dmitry
From: Terry Reedy on
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