Examples
Minimal Example
Call generalimport
before importing any optional dependencies.
from generalimport import generalimport
generalimport("notinstalled")
from notinstalled import missing_func
missing_func()
MissingDependencyException: Optional dependency 'notinstalled' was used but it isn't installed.
Imports fail when they are used, not imported.
This means you don't need to keep checking if the package is installed before importing it.
Simply import your optional package and use it like you would any package and let it fail wherever it fails, with a nice error message.
Tests Showcase
The beauty of this package is that the error raised isn't just any exception.
It has two base classes: unittest.case.SkipTest
and _pytest.outcomes.Skipped
(If available).
This means that if a test method uses an uninstalled optional package then that test is automatically skipped.
This means no more manual skip decorators for optional dependencies!
from generalimport import generalimport
generalimport("optional_uninstalled_package")
from optional_uninstalled_package import missing_func
from unittest import TestCase
class MyTest(TestCase):
def test_missing_func(self):
self.assertEqual(3, missing_func(1, 2))
Ran 1 test in 0.002s
OK (skipped=1)
Skipped: Optional dependency 'optional_uninstalled_package' was used but it isn't installed.
Recommended Setup
Put this in your __init__.py
file to affect all imports inside the folder __init__.py
resides in.
from generalimport import generalimport
generalimport("your", "optional", "dependencies")
generalimport("*")
makes it handle all names (If missing of course)
:warning: generalimport("*")._scope = None
disables the scope
- Makes it handle missing imports anywhere
- For example it will override
pandas
internal custom optional dependency handling
How It Works
- When
generalimport
is instantiated it creates a new importer for sys.meta_path
. - This importer will return 'fake' modules for matching names and scope.
- The scope ensures only your own imports are faked.
- The fake module will recursively return a FakeModule instance when asked for an attribute.
- When used in any way (__call__, __add__, __str__ etc) it raises
generalimport.MissingDependencyException
. - This exception has the 'skip-exceptions' from
unittest
and pytest
as bases, which means that tests will automatically be skipped.