Skip to content

Instantly share code, notes, and snippets.

@eferro
Created October 21, 2012 18:31
Show Gist options
  • Save eferro/3928018 to your computer and use it in GitHub Desktop.
Save eferro/3928018 to your computer and use it in GitHub Desktop.
Import module and/or symbol dynamically from name (string)
import importlib
class Importer(object):
@staticmethod
def import_module(module_name):
return importlib.import_module(module_name)
@staticmethod
def get_symbol(symbol_name):
module_name = Importer._extract_module_name(symbol_name)
final_symbol_name = Importer._extract_final_symbol_name(symbol_name)
module = importlib.import_module(module_name)
try:
return getattr(module, final_symbol_name)
except AttributeError:
raise ImportError()
@staticmethod
def _extract_module_name(symbol_name):
return '.'.join(symbol_name.split('.')[:-1])
@staticmethod
def _extract_final_symbol_name(symbol_name):
return symbol_name.split('.')[-1:][0]
import_module = Importer.import_module
get_symbol = Importer.get_symbol
import unittest
from hamcrest import *
import importer
class ImporterTest(unittest.TestCase):
def test_import_os_by_name(self):
imported_os = importer.import_module('os')
import os
assert_that(imported_os, equal_to(os))
def test_import_os_path(self):
imported_os_path= importer.import_module('os.path')
import os.path
assert_that(imported_os_path, equal_to(os.path))
def test_try_to_import_not_existing_module_should_raise_import_error(self):
self.assertRaises(ImportError, importer.import_module, 'whatever')
def test_get_isdir_function_by_name(self):
import os.path
assert_that(importer.get_symbol('os.path.isdir'), equal_to(os.path.isdir))
def test_non_existing_symbol_should_raise_import_error(self):
self.assertRaises(ImportError, importer.get_symbol, 'os.path.whatever')
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment