I have this variable that I want to cast to custom class
obj = {'model': 'User'}
User is a Aqlalchemy model name.
I want something like this:
user = User()
and of course this wouldn't work:
use = obj['model']()
thanks in advance
You can store your class in a dictionary and then by your json input you can convert json to a dictionary from model to class:
import json
class User:
def __str__(self) -> str:
return "User Class"
class Admin:
def __str__(self) -> str:
return "Admin Class"
models= {"User": User, "Admin": Admin}
jsonStr = '{"model1":"User","model2":"Admin"}'
obj = json.loads(jsonStr)
convertedObj = {k:models[v] for k,v in obj.items()}
print(convertedObj["model1"]())
print(convertedObj["model2"]())
The output will be:
User Class
Admin Class
obj = {'model': User}?