JasonTS JasonTS - 1 year ago 108
Python Question

How to create objects on the fly in python?

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], 'test2': 'something else', 'test3': 1}

which makes the template look untidy. so I think it's better to just create an object which is like:

class testclass():
self.test = [a1,a2,b2]
self.test2 = 'someting else'
self.test3 = 1
testobj = testclass()

so I can do:

{{ testobj.test }}
{{ testobj.test2 }}
{{ testobj.test3 }}

instead of calling the dictionary.

Since I just need that object once, is it possible to create it without writing a class first? Is there any short-hand code? Is it ok to do it like that or is it bad Python?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download