Skip to content

Instantly share code, notes, and snippets.

@frenchtoast747
Created October 4, 2015 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frenchtoast747/6952847b8e0634ce9054 to your computer and use it in GitHub Desktop.
Save frenchtoast747/6952847b8e0634ce9054 to your computer and use it in GitHub Desktop.
Lazy Importing
class lazy_import(object):
"""
The main purpose for this is to make module level coverage work :(
If/When nose2 figures out how to fix the coverage problem, or if
a new test discovery method or loader is used, this should be removed
in favor of real imports.
"""
def __init__(self, python_path):
self.python_path = python_path
self._obj = None
def _do_import(self):
parts = self.python_path.split('.')
module_path = '.'.join(parts[:-1])
obj = parts[-1]
module = __import__(module_path, globals(), locals(), fromlist=[obj])
self._obj = getattr(module, obj)
def __call__(self, *args, **kwargs):
if self._obj is None:
self._do_import()
return self._obj(*args, **kwargs)
def __getattr__(self, item):
if self._obj is None:
self._do_import()
return getattr(self._obj, item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment