diff --git a/.travis.yml b/.travis.yml index 81ad6e5..fe9e18c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,6 +3,15 @@ python: - '2.7' install: - make compile + script: - make test -- make publish + +publish: + make publish + +stages: + - compile + - test + - publish + if: branch = master diff --git a/extras/__init__.py b/extras/__init__.py new file mode 100644 index 0000000..7359330 --- /dev/null +++ b/extras/__init__.py @@ -0,0 +1,52 @@ +""" + python package "extras" module + + *Attempt* to import a library, without knowing if it's installed. + May optionally throw an error + + +""" +import inspect +import logging + +logger = logging.getLogger(__name__) + +MODULES={} + + +def __getitem__(module_name): + """ hash interface with extras, throw error if + module doesn't exist. + """ + module = MODULES.get(module_name) + + if module: + return module + + module = __import__(module_name) + MODULES[module_name] = module + + return module + + +def get(module_name): + """ return package if package exists, None if fails. + should cache imported modules + """ + + try: + return __getitem__(module_name) + + except ImportError as err: + logger.info("Excluding `%s` because it's not installed."%module_name) + + +def not_important(module_name): + """ `import` directly to the class binding. + reference the class just like you used `import`. + `module_name is None` checks for existance. + """ + stack = inspect.stack() + klass = stack[1][0].f_locals[module_name] = get(module_name) + +optional = not_important diff --git a/tests/unit/extras/getter_test.py b/tests/unit/extras/getter_test.py new file mode 100644 index 0000000..30270c4 --- /dev/null +++ b/tests/unit/extras/getter_test.py @@ -0,0 +1,23 @@ +from pytest import raises, mark +import extras + +class TestExtrasGetters: + def test_get_module(self): + numpy = extras.get('numpy') + # assert type(numpy.array([1,2,3,4,5])) == numpy.array + arr = numpy.array([0,1,2,3,4,5]) + + assert arr[0] == 0 + + + def test_get_non_existing_module(self): + nopy = extras.get('nopy') + + assert nopy is None + + + @mark.skip("nice to have, jacking module") + def test_brackets(self): + numpy = extras['numpy'] + assert isinstance(numpy.array([1,2,3,4,5]), numpy.array) + diff --git a/tests/unit/extras/optional_import_test.py b/tests/unit/extras/optional_import_test.py new file mode 100644 index 0000000..108524f --- /dev/null +++ b/tests/unit/extras/optional_import_test.py @@ -0,0 +1,15 @@ +from pytest import raises +from extras import not_important +not_important('numpy') +not_important('garbage') + + +class TestExtrasGetters: + def test_import_module(self): + arr = numpy.array([0,1,2,3,4,5]) + + assert arr[0] == 0 + + + def test_non_existing_module(self): + assert garbage is None