Skip to content

Instantly share code, notes, and snippets.

@bradwright
Created September 2, 2009 15:32
Show Gist options
  • Save bradwright/179767 to your computer and use it in GitHub Desktop.
Save bradwright/179767 to your computer and use it in GitHub Desktop.
def get_class(class_to_get, *args, **kwargs):
"""Will get the class regardless of whether it's a module or not:
>>> get_class('module.MyClassName')
MyClassName()
"""
try:
dot = class.rindex('.')
except ValueError:
pass
else:
module, class_name = class[:dot], class[dot+1:]
try:
mod = __import__(module, {}, {}, [''])
except ImportError, error:
# this should fail regardless
raise ImportError, error
else:
class_to_get = getattr(mod, class_name)
return class_to_get(*args[1:], **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment