An empty object with dynamic attributes (expando)
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Jun 4 01:03:13 EDT 2010
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
More information about the Python-list
mailing list