ImportError
ImportError
Stack trace
Traceback (most recent call last):
File "app.py", line 10, in <module>
from modal import Stub
ImportError: cannot import name 'Stub' from 'modal' (unknown location) Why it happens
This error happens because the Modal stub run executes in a local environment where the Python import system cannot locate the 'modal' package or the specific module. It often occurs if the package is not installed, the environment is misconfigured, or the import path is incorrect.
Detection
Check for ImportError exceptions during stub run startup and verify that the 'modal' package is installed and accessible in the current Python environment before running the stub.
Causes & fixes
Modal package is not installed in the local Python environment
Install the modal package using pip install modal in the environment where the stub run is executed.
Incorrect import statement or module name in the stub code
Verify and correct the import statement to match the Modal SDK's current API, e.g., use 'from modal import Stub' if Stub is the correct class.
Running the stub in a virtual environment where modal is not installed
Activate the correct virtual environment or install modal inside the active environment before running the stub.
Python path or environment variables misconfigured, causing import failures
Ensure PYTHONPATH and environment variables include the directories where modal is installed, or run the stub from the correct working directory.
Code: broken vs fixed
from modal import Stub # ImportError occurs here if modal is missing or misconfigured
stub = Stub('my-app')
@stub.function
def hello():
print('Hello from Modal!')
if __name__ == '__main__':
stub.run(hello) import os
import sys
# Ensure modal package is installed and environment is correct
from modal import Stub # Fixed import after installing modal
stub = Stub('my-app')
@stub.function
def hello():
print('Hello from Modal!')
if __name__ == '__main__':
stub.run(hello) # Runs successfully after fix Workaround
If you cannot install modal immediately, run the stub code in a Docker container or cloud environment where modal is pre-installed to bypass local import issues.
Prevention
Use virtual environments consistently and include modal in your project's requirements.txt or pyproject.toml to ensure the package is installed before running stubs locally.