I have a cursor object from a MongoDB find() query. This is essentially an iterable object which is made up of multiple dictionary entries.
I want to iterate over the cursor, take each dictionary in turn and convert it into a specific class instance, the type of which is defined inside the dictionary as a key (i.e. of the form dict['class_type']='class_type'). I want to create variables to reference these new class instances, with names defined by another dictionary key, i.e. dict['variable_name'] = 'name'. These names will be unique.
So far, I have tried the following:
def mongo_query_to_variable(mongo_query):
for obj in mongo_query:
class_type = obj['class_type']
var_name = obj[key_for_var_name]
exec(var_name + '=' + class_type + '(**obj)', globals())
This code seems to work when I implement it line by line in the shell but not when I try to use it as a function. I get the error:
NameError: name 'class_type' is not defined
I know it is better to try and avoid eval/exec, but am not sure how else I could dynamically choose the class type with the class_type string. The last line is essentially trying to replicate the accepted answer (2nd part) from this similar question, but with dynamic variable and class names: Convert Python dict to object?. The part of the code which goes in the class init is contained in a base class and inherited.
I have the global in there because the query will be of variable length, and I am not really sure how to return a dynamic number of variables and assign them names defined within the function. I have heard that it is better to avoid global so is there a better way of assigning the class instances to variables?
Any advice is appreciated; I am pretty new to programming and am aware I might be approaching this problem in the wrong way.
Cheers