Created
September 21, 2022 04:58
-
-
Save hanjinliu/31d5752d424d03575a66bd9ec8adffb6 to your computer and use it in GitHub Desktop.
Import modules into the IPython shell without overhead
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
class LazyImporter: | |
def __init__(self, name: str, alias: str = None): | |
self._name = name | |
self._alias = alias or name | |
def __repr__(self): | |
return repr(self._mod) | |
def __str__(self): | |
return str(self._mod) | |
def __getattr__(self, name): | |
return getattr(self._mod, name) | |
@property | |
def _mod(self): | |
from IPython import get_ipython | |
import importlib | |
mod = importlib.import_module(self._name) | |
shell = get_ipython() | |
shell.push({self._alias: mod}) # update namespace | |
return mod | |
np = LazyImporter('numpy', 'np') | |
plt = LazyImporter('matplotlib.pyplot', 'plt') | |
pd = LazyImporter('pandas', 'pd') | |
sns = LazyImporter('seaborn', 'sns') | |
napari = LazyImporter('napari', 'napari') | |
da = LazyImporter('dask.array', 'da') | |
rich = LazyImporter('rich', 'rich') | |
del LazyImporter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment