There maybe (usually is) a better way to do what I’m trying, but I am currently making a list of objects like this:
my_list = [MyObject(d**) for d in db.myobjects.find({...})]
This works great because it creates converts the dictionary objects returned by my database query into “MyObjects”, adding in a bunch of class methods and properties.
How can I do the same thing when the Class name is dynamically inserted at runtime? I can create the classes dynamically using eval() but how can I insert the dictionary objects?
my_list = [eval('FooObject') for d in db.fooobjects.find({...})] # needs kwargs from dicts
Any help would be awesome.
First, consider using
globals()instead ofeval(), especially if the class string is from user input.To your actual question, it works exactly the same way –
eval('FooClass')orglobals()['FooClass']gives you the class itself, it doesn’t instantiate it. That means you can instantiate it by calling it, same as if you know its name ahead of time: