importnb
test specification¶
this notebook is written to test many of the features of importnb
.
these features in this notebook test:
- basic finding and loading
- filtering magics, classes and functions
- lazy loading
- the command line interface
a sentinel for execution¶
the slug
below is used to measure that a module has been executed,
we specifically use this expression to measure the lazy importing system.
from importnb import get_ipython
from pathlib import Path
where = ""
if "__file__" in locals():
where = Path(__file__).as_posix()
slug = "i was printed from {where} \
and my name is {__name__}"
print(slug.format(**locals()))
i was printed from and my name is __main__
implicit markdown docstrings¶
there is a strict separation of code and non-code in notebooks.
to encourage more/better documentation importnb
will use a markdown
cell preceeding a function as a docstring.
as a result, the function_with_a_markdown
docstring will have this markdown cell for a value.
def function_with_a_markdown_docstring():
return # function_with_a_markdown has a docstring defined by the preceeding markdown cell
the same convention holds for classes and async functions.
class class_with_a_markdown_docstring:
... # my docstring is the cell above.
this is not a docstring for class_with_a_string
because it defines its own.
class class_with_a_python_docstring:
"""when a class defines its own docstring the preceeding cell is ignored."""
cell magics¶
%%python
print("i'm only show when cell magics are active.")
i'm only show when cell magics are active.
if get_ipython():
magic_slug = "i'm only show when cell magics are active."
if __import__('sys').platform == "win32": magic_slug += "\n"
else:
magic_slug = f"this was printed from the module named {__name__}"
print(magic_slug)
notebooks as scripts¶
the main block is a python convention we can apply in notebooks imported by importnb.
def get_parser():
from argparse import ArgumentParser, REMAINDER
parser = ArgumentParser("test_parser")
parser.add_argument("--", nargs=REMAINDER, dest="args")
return parser
def main(argv=None):
parser = get_parser()
print("the parser namespace is", parser.parse_args(argv))
this the docstring for the echo
task that echos hello.
def task_echo():
return dict(actions=["echo hello"])
import sys
if __name__ == "__main__":
if "__file__" in locals():
# run this notebook like it is a cli
if "pytest" not in sys.modules:
if "doit" not in sys.modules:
main(sys.argv[1:])
data loaders¶
data loaders can import other file formats. we can hide loading logic underneath import
statements.
if get_ipython() and not where:
from importnb import loaders
display(loaders.Json.load_file("Untitled42.ipynb"))
<module '__main__' from 'Untitled42.ipynb'>