How do I create objects on the fly in Python? I often want to pass information to my Django templates which is formatted like this:
{\'test\': [a1, a2, b2],
You can use built-in type function:
testobj = type('testclass', (object,),
{'test':[a1,a2,b2], 'test2':'something else', 'test3':1})()
But in this specific case (data object for Django templates), you should use @Xion's solution.
for the sake of completeness, there is also recordclass
:
from recordclass import recordclass
Test = recordclass('Test', ['test', 'test1', 'test2'])
foo = Test(test=['a1','a2','b2'], test1='someting else', test2=1)
print(foo.test)
.. ['a1', 'a2', 'b2']