0
# Modal
1
2
Modal is a Python client library for Modal, a serverless cloud computing platform that enables developers to run Python code in the cloud with on-demand access to compute resources. The library provides a comprehensive toolkit for building, deploying, and managing serverless applications including functions, classes, containers, volumes, secrets, and file systems. It features a rich API for defining cloud resources declaratively, supports parallel execution and distributed computing patterns, includes built-in monitoring and logging capabilities, and provides seamless integration with popular Python frameworks and libraries.
3
4
## Package Information
5
6
- **Package Name**: modal
7
- **Language**: Python
8
- **Installation**: `pip install modal`
9
- **Python Requirements**: >= 3.9, < 3.14
10
11
## Core Imports
12
13
```python
14
import modal
15
```
16
17
Common pattern for accessing main classes:
18
19
```python
20
from modal import App, Image, Secret, Volume
21
```
22
23
Alternative import all public APIs:
24
25
```python
26
from modal import *
27
```
28
29
## Basic Usage
30
31
```python
32
import modal
33
34
# Define an application
35
app = modal.App("my-app")
36
37
# Define a custom container image with dependencies
38
image = modal.Image.debian_slim().pip_install("requests", "beautifulsoup4")
39
40
# Define a serverless function
41
@app.function(image=image)
42
def scrape_url(url: str) -> str:
43
import requests
44
from bs4 import BeautifulSoup
45
46
response = requests.get(url)
47
soup = BeautifulSoup(response.content, 'html.parser')
48
return soup.get_text()
49
50
# Local entrypoint to run the function
51
@app.local_entrypoint()
52
def main():
53
result = scrape_url.remote("https://example.com")
54
print(result)
55
56
# Deploy the app
57
if __name__ == "__main__":
58
app.run()
59
```
60
61
## Architecture
62
63
Modal follows a declarative resource model where applications are composed of:
64
65
- **App**: Main container that groups functions, classes, and resources
66
- **Compute Resources**: Functions and Classes that execute in the cloud
67
- **Infrastructure**: Storage (Volumes, NetworkFileSystem), networking (Proxy, Tunnel), and security (Secret)
68
- **Images**: Container definitions that specify the runtime environment
69
- **Scheduling**: Cron jobs and periodic tasks for automated execution
70
71
The library uses the synchronicity pattern to provide both synchronous and asynchronous APIs from a single codebase, enabling flexible usage patterns while maintaining type safety.
72
73
## Capabilities
74
75
### Core Application & Client
76
77
Primary interfaces for defining applications and managing authentication with Modal's cloud platform.
78
79
```python { .api }
80
class App:
81
def __init__(self, name: str): ...
82
def function(self, **kwargs): ... # Decorator
83
def cls(self, **kwargs): ... # Decorator
84
def local_entrypoint(self): ... # Decorator
85
def deploy(self): ...
86
def run(self): ...
87
88
class Client:
89
@classmethod
90
def from_env(cls): ...
91
def lookup(self, label: str): ...
92
```
93
94
[Core Application & Client](./core-application-client.md)
95
96
### Compute Resources
97
98
Functions and classes that execute serverless workloads in Modal's cloud infrastructure.
99
100
```python { .api }
101
class Function:
102
def remote(self, *args, **kwargs): ...
103
def local(self, *args, **kwargs): ...
104
def map(self, inputs): ...
105
def spawn(self, *args, **kwargs): ...
106
107
class FunctionCall:
108
def get(self): ...
109
def cancel(self): ...
110
111
class Cls:
112
@classmethod
113
def from_name(cls, label: str): ...
114
def lookup(self, name: str): ...
115
116
class Sandbox:
117
@classmethod
118
def create(cls, **kwargs): ...
119
def exec(self, command: str): ...
120
def terminate(self): ...
121
```
122
123
[Compute Resources](./compute-resources.md)
124
125
### Container Images
126
127
Container image definitions that specify the runtime environment for functions and classes.
128
129
```python { .api }
130
class Image:
131
@classmethod
132
def debian_slim(cls, python_version: str = None): ...
133
@classmethod
134
def from_registry(cls, tag: str): ...
135
def pip_install(self, *packages: str): ...
136
def run_commands(self, *commands: str): ...
137
def copy_local_file(self, local_path: str, remote_path: str): ...
138
```
139
140
[Container Images](./container-images.md)
141
142
### Storage & Data
143
144
Persistent storage solutions including volumes, network file systems, key-value stores, and cloud bucket mounts.
145
146
```python { .api }
147
class Volume:
148
@classmethod
149
def from_name(cls, label: str): ...
150
@classmethod
151
def persist(cls, label: str): ...
152
153
class NetworkFileSystem:
154
@classmethod
155
def from_name(cls, label: str): ...
156
@classmethod
157
def persist(cls, label: str): ...
158
159
class Dict:
160
@classmethod
161
def from_name(cls, label: str): ...
162
def get(self, key: str): ...
163
def put(self, key: str, value): ...
164
def pop(self, key: str): ...
165
166
class Queue:
167
@classmethod
168
def from_name(cls, label: str): ...
169
def put(self, item): ...
170
def get(self): ...
171
```
172
173
[Storage & Data](./storage-data.md)
174
175
### Infrastructure Services
176
177
Networking, security, and infrastructure services for cloud applications.
178
179
```python { .api }
180
class Secret:
181
@classmethod
182
def from_name(cls, label: str): ...
183
@classmethod
184
def from_dict(cls, mapping: dict): ...
185
186
class Proxy:
187
@classmethod
188
def from_name(cls, label: str): ...
189
190
class Tunnel:
191
@classmethod
192
def create(cls, **kwargs): ...
193
194
class SchedulerPlacement:
195
@classmethod
196
def zone(cls, zone: str): ...
197
```
198
199
[Infrastructure Services](./infrastructure-services.md)
200
201
### Function Decorators & Helpers
202
203
Decorators and helper functions for enhancing function behavior and defining lifecycle methods.
204
205
```python { .api }
206
def method(func): ...
207
def parameter(name: str, default=None): ...
208
def enter(func): ...
209
def exit(func): ...
210
def batched(max_batch_size: int): ...
211
def concurrent(func): ...
212
```
213
214
[Function Decorators & Helpers](./function-decorators-helpers.md)
215
216
### Web & API Integration
217
218
Web application serving capabilities including ASGI, WSGI, and HTTP endpoint support.
219
220
```python { .api }
221
def asgi_app(func): ...
222
def wsgi_app(func): ...
223
def web_endpoint(func): ...
224
def fastapi_endpoint(func): ...
225
def web_server(func): ...
226
```
227
228
[Web & API Integration](./web-api-integration.md)
229
230
### Scheduling & Reliability
231
232
Task scheduling and retry policies for automated and resilient execution.
233
234
```python { .api }
235
class Cron:
236
def __init__(self, cron_string: str): ...
237
238
class Period:
239
@classmethod
240
def days(cls, n: int): ...
241
@classmethod
242
def hours(cls, n: int): ...
243
@classmethod
244
def minutes(cls, n: int): ...
245
@classmethod
246
def seconds(cls, n: int): ...
247
248
class Retries:
249
def __init__(
250
self,
251
max_retries: int = 3,
252
backoff: float = 2.0,
253
initial_delay: float = 1.0
254
): ...
255
```
256
257
[Scheduling & Reliability](./scheduling-reliability.md)
258
259
### Runtime Utilities
260
261
Utilities for runtime context, debugging, and execution control within Modal functions.
262
263
```python { .api }
264
def current_function_call_id() -> str: ...
265
def current_input_id() -> str: ...
266
def is_local() -> bool: ...
267
def interact(): ...
268
def enable_output(): ...
269
def forward(**kwargs): ...
270
```
271
272
[Runtime Utilities](./runtime-utilities.md)
273
274
### Utility Classes
275
276
General utility classes for error handling, file pattern matching, and package information.
277
278
```python { .api }
279
__version__: str # Package version
280
281
class Error(Exception): ...
282
283
class FilePatternMatcher:
284
def __init__(self, patterns: list): ...
285
def matches(self, path: str) -> bool: ...
286
```
287
288
[Utility Classes](./utility-classes.md)
289
290
## Common Patterns
291
292
### Function with Custom Environment
293
294
```python
295
import modal
296
297
app = modal.App()
298
299
@app.function(
300
image=modal.Image.debian_slim().pip_install("numpy", "pandas"),
301
secrets=[modal.Secret.from_name("my-secret")],
302
volumes={"/data": modal.Volume.from_name("my-volume")}
303
)
304
def process_data(filename: str):
305
import pandas as pd
306
df = pd.read_csv(f"/data/{filename}")
307
return df.describe().to_dict()
308
```
309
310
### Scheduled Function
311
312
```python
313
from modal import App, Cron
314
315
app = App()
316
317
@app.function(schedule=Cron("0 0 * * *")) # Daily at midnight
318
def daily_report():
319
# Generate and send daily report
320
print("Running daily report...")
321
```
322
323
### Class with Lifecycle Methods
324
325
```python
326
from modal import App, enter, exit, method
327
328
app = App()
329
330
@app.cls()
331
class MyService:
332
@enter()
333
def setup(self):
334
# Initialize resources
335
self.client = create_client()
336
337
@exit()
338
def cleanup(self):
339
# Clean up resources
340
self.client.close()
341
342
@method()
343
def process(self, data):
344
return self.client.process(data)
345
```