ericMTR
ericMTR

Reputation: 211

Creating an empty object with nested attributes in Python

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

Answers (2)

metmirr
metmirr

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

Raja Sudhan
Raja Sudhan

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

Related Questions