@session.function() decorator for running Python functions in sandboxes. It’s intended for developers who want to offload individual Python computations to isolated environments without managing a sandbox lifecycle directly, and explains how to define remote functions, which argument and return types the API supports, and when this API is the right fit.
Overview
The function decorator API lets you execute Python functions in isolated sandbox containers. Use it when you want to run discrete Python work remotely while keeping your calling code simple:Basic usage
Define functions
Decorate functions with@session.function():
Call functions
Call.remote() on the decorated function to execute in the sandbox:
Execution methods
Run in parallel with map()
Execute across multiple inputs:Run locally with local()
Run locally without a sandbox, which is useful for testing:Argument and return types
Remote functions transfer arguments and return values as JSON. Both must be JSON-serializable: dictionaries, lists, strings, numbers, booleans, andNone.
TypeError before the sandbox starts:
Example output
return value is not JSON-serializable.
JSON objects support string keys only. A dictionary keyed by integers, floats, or booleans is rejected rather than converted, so the types your function receives in the sandbox match the types you passed.
To work with NumPy arrays, pandas DataFrames, or custom class instances, convert them to JSON-compatible values before you call the function, then reconstruct them inside it:
Closures and globals
Closure variables
Functions capture variables from their enclosing scope:Global variables
The decorator serializes referenced globals with the function:Container image
Override the container image for specific functions:Error handling
Function exceptions propagate to the caller:When to use functions compared to sandboxes
Use the following table to decide whether the function decorator API or the sandbox API is a better fit for your workload.Limitations
The function API is intentionally simple. For complex workflows:- Retries and backoff: Implement in calling code.
- Task dependencies and DAGs: Use a workflow orchestrator such as Airflow or Prefect.
- Complex scheduling: Use the sandbox API directly.