I am using mongoengine in python as an ORM. Now I have a situation where I have a class, actually the a model, of the form:
from mongoengine import *
class SomeDetails(Document):
alias = StringField(required=True)
version = StringField(required=True)
author = StringField(required=True)
someName = StringField(required=True)
Now I need to create the object of this class (and hence a document at runtime)
I can create an object of a normal class at runtime by using inspection, something like this:
from inspect import isclass
# moduleImport is a method made to facilitate importing of modules at runtime.
new_module = moduleImport('myModule')
classes = [x for x in dir(new_module) if isclass(getattr(new_module, x))]
class_object = getattr(new_module, classes[0])
instance = class_object()
And the above works perfectly. I am able to create an object at runtime and then use it as I wish.
However, in the former case above, when I need to create an object (or actually a mongo document in this case), as per the mongoengine documentation here and here, I need to create the object something like this:
docObject = SomeDetails(alias=value, version=value, author=value, someName=value)
docObject.save() # to save the document in the mongodb
wherein I need to specify the values for each of the keyword arguments while creating the object of the class, so that the document gets saved successfully.
So in this case, if I try creating the object of the SomeDetails class at runtime (as shown in the inspect example above) how can I provide these keyword arguments at the runtime while creating the object?
An important catch
So the keyword arguments are also not known before hand. They too are fetched at runtime. At runtime, before object creation, yes, I do know the list of keyword args and it's values, which is available to me as a dictionary as :
{alias:"a", version:"b", author:"c", someName:"d"}
but even then, this dic itself is available only at runtime.
You can try this:
data = {alias:"a", version:"b", author:"c", someName:"d"}
instance = class_object(**data)
More on **kwargs here