This guide covers the @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, choose serialization modes, and decide 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:
With tuples for multiple arguments:
Run locally with local()
Run locally without a sandbox, which is useful for testing:
Serialization modes
Choose a serialization mode based on the types of arguments and return values your function uses.
JSON (default)
Safe and human-readable, but limited to JSON-serializable types:
Pickle
Supports complex Python objects:
Use pickle when you need:
- NumPy arrays.
- Pandas DataFrames.
- Custom class instances.
- Complex nested objects.
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.
Complete example
The following example combines the concepts in this guide. It shows JSON and pickle serialization, single and parallel execution, and a NumPy workflow in one session:
Last modified on May 29, 2026