1

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?

3
  • how do you want to use this? Commented Dec 9, 2016 at 12:41
  • Well the class constructor would be the Form class from WTForms. But in this case I only want to create a 'fake' object which only contains those attributes: form.foo.data or form.bar.data and so on. Commented Dec 9, 2016 at 12:46
  • @Navidad20 It's for a test case. I need to assign the values to those attributes manually. Commented Dec 9, 2016 at 12:54

2 Answers 2

3

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}) 
Sign up to request clarification or add additional context in comments.

1 Comment

This way looks good, but I think we have a "better" way to do this with MagicMock, like in this
0

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
()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.