Skip to content

Instantly share code, notes, and snippets.

@clarksun
Created September 20, 2017 07:10
Show Gist options
  • Save clarksun/a503909618096c1aee1cda0ddc36b4a0 to your computer and use it in GitHub Desktop.
Save clarksun/a503909618096c1aee1cda0ddc36b4a0 to your computer and use it in GitHub Desktop.
load_object by path
# frontera/utils/misc.py
from importlib import import_module
def load_object(path):
"""Load an object given its absolute object path, and return it.
object can be a class, function, variable o instance.
path ie: 'myproject.frontier.models.Page'
"""
try:
dot = path.rindex('.')
except ValueError:
raise ValueError("Error loading object '%s': not a full path" % path)
module, name = path[:dot], path[dot+1:]
try:
mod = import_module(module)
except ImportError as e:
raise ImportError("Error loading object '%s': %s" % (path, e))
try:
obj = getattr(mod, name)
except AttributeError:
raise NameError("Module '%s' doesn't define any object named '%s'" % (module, name))
return obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment