1

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

2
  • 2
    Is there a reason you aren't doing obj = {'model': User}? Commented Apr 7, 2020 at 19:42
  • Yes, actually, I'm getting a json from other service, it would be result of service which is String so can not be object type User Commented Apr 8, 2020 at 11:54

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.