In this guide, We will walk you through two methods to achieve this: using a package to import directly from a notebook, and saving your functions to a Python file and importing them as a module.
Importing from a Python file
The most straightforward and recommended method is to save your functions in a Python file (.py) and then import them into your notebooks. Here’s how to do it:
another_file.py
def greetFromAnotherFile(name):
return f"Sup, {name} from another file!"
Notebook 1
import sys
import importlib # !pip install importlib
sys.path.append('.')
import another_file
importlib.reload(another_file)
print(another_file.greetFromAnotherFile(name))
Importing from another notebook
another_notebook
def greetFromAnotherNotebook(name):
return f"Hello, {name} from another notebook!"
After writing a function or anything else that you would want to use in another notebook you will need to export the Deepnote Notebook into .ipynb file and than drag and drop it into files.
Notebook 1
import ipynb
%run imported_another_notebook.ipynb
print(greetFromAnotherNotebook(name))
Example project structure
├── Notebook 1
├── another_notebook
----------------------------------------------------------------------------------
.
├── work/
├── requirements.txt
├── another_file.py
├── imported_another_notebook.ipynb #after exporting
└── .deepnote
Examples
For the showcase, I created an example notebook where you can try it yourself and an example app for view.
Conclusion
Deepnote offers flexibility in how you can structure and reuse code within your projects. Whether you prefer to save functions in a Python file or import them directly from other notebooks using nbimporter, you can keep your code organized and maintainable. If you encounter further issues, feel free to contact our support for assistance. Happy coding in Deepnote!
This guide should help you efficiently import functions from other notebooks or Python files in Deepnote, making your workflow smoother and more productive. If you encounter any issues, please get in touch with our support. Happy hacking in Deepnote! 🐍