I want to implement something a bit similar to django fixture system where in fixture you set model
property which indicates a model class of fixture. It looks something like this
my_app.models.my_model
My question is what is the standard way to process such a string in order to create the instance of the class pointed by this "path". I think it should look something like:
- Split it to module name and class name parts
- Load module (if not loaded)
- Acquire class from module by its name
- Instantiate it
How exactly should I do it?
Edit: I came up with a dirty solution:
def _resolve_class(self, class_path):
tokens = class_path.split('.')
class_name = tokens[-1]
module_name = '.'.join(tokens[:-1])
exec "from %s import %s" % (module_name, class_name)
class_obj = locals()[class_name]
return class_obj
That does it's job however is dirty because of usage of exec and possibility of manipulating execution by malicious preparation of fixtures. How should it be done properly?