Created
October 29, 2012 16:45
-
-
Save lukaszb/3974771 to your computer and use it in GitHub Desktop.
Imports python object from given path
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 import_obj(obj_path): | |
""" | |
Returns object from the given path. | |
For example, in order to get function located at | |
``os.path.abspath``: | |
abspath = import_obj('os.path.abspath') | |
:raises ImportError: If object at the given path couldn't be retrieved | |
""" | |
if '.' not in obj_path: | |
return __import__(obj_path, {}, {}, []) | |
splitted = obj_path.split('.') | |
mod_path = '.'.join(splitted[:-1]) | |
obj_name = splitted[-1] | |
try: | |
class_mod = __import__(mod_path, {}, {}, [obj_name]) | |
return getattr(class_mod, obj_name) | |
except ImportError: | |
msg = "Couldn't locate python object at the given path: %r" % obj_path | |
raise ImportError(msg) | |
import os | |
import os.path | |
import unittest | |
from io import StringIO | |
class ImportObjTest(unittest.TestCase): | |
def test_simple_import(self): | |
self.assertEqual(import_obj('os'), os) | |
def test_simple_import_of_submodule(self): | |
self.assertEqual(import_obj('os.path'), os.path) | |
def test_import_function(self): | |
self.assertEqual(import_obj('os.path.abspath'), os.path.abspath) | |
def test_import_class(self): | |
self.assertEqual(import_obj('io.StringIO'), StringIO) | |
if __name__ == '__main__': | |
unittest.main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment