Created
July 29, 2013 17:22
-
-
Save buchanae/6105943 to your computer and use it in GitHub Desktop.
Get Python class by name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, that was a great tip for my task.