Concise way of reloading with alias?
davidleejy opened this issue · comments
Hello community,
Does anyone know a concise way of achieving the following:
# Goal: Import abc123.ipynb and alias it as xxx.
from importnb import Notebook
from importlib import reload
with Notebook(lazy=True):
if __name__ == '__main__':
# This conditional block is meant to run when executing the current .py file directly.
import abc123
xxx = reload(abc123)
else:
import abc123 as xxx # This statement is meant to be run by processes importing current .pyfile.
xxx.foo()
Note that if lazy=False
, abc123.ipynb
is imported twice when executing the first conditional block (if __name__ == '__main__':
); doubling the time needed to import it.
Help is appreciated :)
EDIT:
code could be:
from importnb import Notebook
from importlib import reload
with Notebook(lazy=True):
import abc123 as xxx # Lazy load.
xxx = reload(xxx) if __name__ == '__main__' else None # Eager loading when executing current .ipynb file directly.
assert xxx.__file__.endswith('.ipynb') # Check in case shadowed by other imports
As of writing this closing comment, no one has yet advised/chimed in on this issue ticket.
It turns out that importlib
& importnb
don't communicate with one another; if importlib
were to already have imported abc.ipynb
(via reload()
), importnb
's import will still proceed to import abc.ipynb
. As such, abc.ipynb
is executed twice, doubling the import time for an .ipynb file that could potentially be time-consuming to execute.
P.S. The comments in my code snippets above may not accurately reflect the behavior of importnb & importlib.