Reputation: 211
I'm trying to create an empty object which contains nested attributes like this:
form = type('', (), {})()
form.foo.data = ''
But I get following attribute error:
>>> form = type('', (), {})()
>>> form.foo.data = ''
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'data'
How should I construct the object to accomplish that?
Upvotes: 1
Views: 930
Reputation: 4312
I dont get your point but you may use namedtuple
:
>>>from collections import namedtuple
>>>foo = namedtuple('foo', "data tuple dict")
>>>foo.data = ""
''
>>> foo.tuple = ()
>>> foo.tuple
()
Upvotes: 0
Reputation: 121
As per the type function , the third argument should be in the form of dictionary. So, for nested attributes, you can create the object before itself and then use it in the dictionary. Something like this might work -
da = type('',(),{'data':1})
a = type('',(),{'foo':da})
Upvotes: 3