Last active
October 28, 2020 06:59
-
-
Save warabanshi/25d7ade28e82162ac3ed1ba6482dd841 to your computer and use it in GitHub Desktop.
create subclass' instance from base class and target class name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def all_subclasses(model): | |
"""Gets the model from a given key.""" | |
return set(model.__subclasses__()).union([s for c in model.__subclasses__() for s in all_subclasses(c)]) | |
def get_model_from_key(model, key): | |
models = {klass.__name__: klass for klass in all_subclasses(model)} | |
return models.get(key, None) | |
class BaseModel(object): | |
pass | |
class Testdesu(BaseModel): | |
pass | |
val = {'class_name': 'Testdesu'} | |
try: | |
klass = get_model_from_key(BaseModel, val['class_name']) | |
obj = klass() | |
except (KeyError, TypeError): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment