Sometimes i need to create an anonymous class instance in python, just like c#:
var o= new {attr1=\"somehing\", attr2=344};
but in python i
while this is not precisely a single statement I think creating a wrapper around the magic of the accepted answer makes it by far more readable.
import inspect
# wrap the type call around a function
# use kwargs to allow named function arguments
def create_type(name, **kwargs):
return type(name, (object,), kwargs)
# example call to make a structure
p = create_type('foobar', xxx='barfoo', seti=0)
assert p.xxx == 'barfoo'
assert p.seti == 0
print inspect.getmembers(p)
Output
[('__class__', ),
('__delattr__', ),
('__dict__', ),
('__doc__', None),
('__format__', ),
('__getattribute__', ),
('__hash__', ),
('__init__', ),
('__module__', '__main__'),
('__new__', ),
('__reduce__', ),
('__reduce_ex__', ),
('__repr__', ),
('__setattr__', ),
('__sizeof__', ),
('__str__', ),
('__subclasshook__', ),
('__weakref__', ),
# here they are
('seti', 0),
('xxx', 'barfoo')]
from collections import namedtuple
d = { 'a' : 'foo', 'b' : 'bar' }
foobar = namedtuple('foobar', d.keys())(**d)
print foobar
Output
Python 2.7.5 (default, May 30 2013, 16:55:57) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import namedtuple
>>> d = { 'a' : 'foo', 'b' : 'bar' }
>>> foobar = namedtuple('foobar', d.keys())(**d)
>>> print foobar
foobar(a='foo', b='bar')
>>>