Skip to content

Latest commit

 

History

History
72 lines (47 loc) · 2.4 KB

File metadata and controls

72 lines (47 loc) · 2.4 KB

Adding External Code

If you want to use your own Python modules or scripts in Jupyter notebooks, follow these steps to upload them easily.

1. Prepare your external code

Organize your external code and follow Python packaging best practices. Set up the right folder structure, add an __init__.py file, and list any required dependencies.

Suggested Directory Structure:

src/
|-- PYTHON_PROJ_NAME/
|   |-- __init__.py
|   |-- my_script.py
|   |-- subpackage/
|       |-- __init__.py

What goes in __init__.py?

Think of __init__.py as the file that tells Python “this folder is a package”.

If you leave it empty, that is perfectly fine—the package will still import correctly. When you want to make notebooks feel friendlier, you can re-export helper functions so users can discover them more easily:

# src/PYTHON_PROJ_NAME/__init__.py
from .my_script import run_analysis, load_config

__all__ = ["run_analysis", "load_config"]

Each folder that you plan to import (for example, src/subpackage/) should also have its own __init__.py. Keep it empty unless you want to expose selected helpers from that subpackage.

If you need further readings on __init__.py, check out this quick Geeks for Geeks tutorial or the Real Python guide.

2. Upload your external code to the repository

Go to the src folder in your repository and upload your files or folders there.

Upload external code GIF

3. How to import into your notebook

Once uploaded, your external code will be available to your notebooks as a package. To use it, import it as shown in the examples below:

Import the whole package:

import PYTHON_PROJ_NAME

If your folder under src/ is called celltools, then import celltools will work because src/celltools/__init__.py exists.

Import function:

from PYTHON_PROJ_NAME import my_script

Import submodule:

from PYTHON_PROJ_NAME.subpackage import submodule1

← Previous            🏠 Home            Next →