Skip to content

Instantly share code, notes, and snippets.

@johtso
Created December 10, 2011 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johtso/1455217 to your computer and use it in GitHub Desktop.
Save johtso/1455217 to your computer and use it in GitHub Desktop.
load_object monkeypatch
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: 'scrapy.contrib.downloadermiddelware.redirect.RedirectMiddleware'
"""
# monkeypatch
if not isinstance(path, basestring):
return path
# monkeypatch
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, {}, {}, [''])
except ImportError, 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