[Python-ideas] anonymous object support
Masklinn
masklinn at masklinn.net
Sun Jul 24 18:07:03 CEST 2011
On 2011-07-24, at 16:30 , Antoine Pitrou wrote:
> If that's all you need, you just have to write a convenience function
> that you put in some utilities module:
>
> class AnonymousObject:
> pass
>
> def make(**kwargs):
> obj = AnonymousObject()
> for k, v in kwargs.items():
> setattr(obj, k, v)
> return obj
>
>
> and then:
>
>>>> from myutils import make
>>>> obj = make(foo=1, bar=lambda x: x)
>>>> obj.foo
> 1
>>>> obj.bar(1)
> 1
An other option would be to create an anonymous type on the fly to get
methods as well (without having to get a hold on the instancemethod
constructor):
>>> def make(**kwargs):
>>> return type('', (), kwargs)()
>>> obj = make(foo=1, bar=lambda self, x: x)
>>> obj.foo
1
>>> obj.bar(2)
2
although it makes attributes provided via kwargs into class
attributes (which probably does not matter since the class is unique
to the object)
More information about the Python-ideas
mailing list