-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Via #39
- Loading branch information
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
|
||
""" | ||
Lazy module loader. | ||
Code adapted from TensorFlow. | ||
""" | ||
|
||
import importlib | ||
import types | ||
from typing import Dict, Any | ||
|
||
|
||
class LazyLoader(types.ModuleType): | ||
"""Lazily import a module, mainly to avoid pulling in large dependencies. | ||
""" | ||
|
||
def __init__(self, local_name: str, parent_module_globals: Dict[str, Any]): | ||
self._local_name = local_name | ||
self._parent_module_globals = parent_module_globals | ||
name = f'{parent_module_globals["__package__"]}.{local_name}' | ||
super(LazyLoader, self).__init__(name) | ||
|
||
def _load(self): | ||
"""Load the module and insert it into the parent's globals.""" | ||
# Import the target module and insert it into the parent's namespace | ||
module = importlib.import_module(self.__name__) | ||
self._parent_module_globals[self._local_name] = module | ||
|
||
# Update this object's dict so that if someone keeps a reference to the | ||
# LazyLoader, lookups are efficient (__getattr__ is only called on lookups | ||
# that fail). | ||
self.__dict__.update(module.__dict__) | ||
|
||
return module | ||
|
||
def __getattr__(self, item): | ||
module = self._load() | ||
return getattr(module, item) | ||
|
||
def __dir__(self): | ||
module = self._load() | ||
return dir(module) | ||
|