Skip to content

Instantly share code, notes, and snippets.

@warabanshi
Last active October 28, 2020 06:59
Show Gist options
  • Save warabanshi/25d7ade28e82162ac3ed1ba6482dd841 to your computer and use it in GitHub Desktop.
Save warabanshi/25d7ade28e82162ac3ed1ba6482dd841 to your computer and use it in GitHub Desktop.
create subclass' instance from base class and target class name
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