Skip to content

Instantly share code, notes, and snippets.

@buchanae
Created July 29, 2013 17:22
Show Gist options
  • Save buchanae/6105943 to your computer and use it in GitHub Desktop.
Save buchanae/6105943 to your computer and use it in GitHub Desktop.
Get Python class by name
def get_class(name):
# Reflection: try to get the exception class
# Try to split the name on dots,
# in case it contains a module path
parts = name.split('.')
if len(parts) == 1:
# If it didn't have a module path,
# try loading the class from built-ins
try:
m = __import__('builtins')
except ImportError:
m = __import__('__builtin__')
m = getattr(m, parts[0])
else:
# If it did have a module path,
# load the module and then get the class
module = ".".join(parts[:-1])
m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
return m
@ivan3rd
Copy link

ivan3rd commented Jan 27, 2022

Thanks, that was a great tip for my task.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment