# Functions

Call your Modal functions with remote, spawn and map, or deploy them and call them by name: each call runs your code as a local process and returns its real result.

To test code that calls Modal functions, define and call them as you do on Modal: the simulator runs each call as a local process and returns your function's real result. Save this as `orders.py`:

```python
import time

import modal

app = modal.App("orders")

@app.function()
def total(prices, tax=0.0):
    return round(sum(prices) * (1 + tax), 2)

@app.function(timeout=10)
def slow():
    time.sleep(60)

if __name__ == "__main__":
    with app.run():
        print(total.remote([10, 20], tax=0.1))
        print(total.spawn([1, 2, 3]).get(timeout=30))
        print(list(total.map([[1], [2, 3]])))
        try:
            slow.remote()
        except modal.exception.FunctionTimeoutError as exc:
            print(type(exc).__name__)
```

Put the `modal` version that [The Python your code runs on](https://www.rystic.ai/docs/simulators/modal/features/python-runtime.md) names in place of `<version>`, point the SDK at the simulator and run the file:

<!-- example: skip network -->
```bash
pip install -q "modal==<version>"
export MODAL_SERVER_URL="$RYSTIC_URL" MODAL_TOKEN_ID=ak-example MODAL_TOKEN_SECRET=as-example
python3 orders.py
# -> 33.0
# -> 6.0
# -> [1.0, 5.0]
# -> FunctionTimeoutError
```

The last line arrives about 10 seconds after the call: a function's `timeout` counts real seconds.

## Give a function its variables

`env=` and `secrets=` on a function reach its code as environment variables, from `modal.Secret.from_dict` or from a named secret. A variable its image sets with `Image.env` reaches it too, and `env=` replaces one of the same name. Save this as `settings.py`:

```python
import os

import modal

app = modal.App("settings")

image = modal.Image.debian_slim().env({"REGION": "us", "STAGE": "test"})

@app.function(image=image, env={"REGION": "eu"}, secrets=[modal.Secret.from_dict({"API_KEY": "test-key"})])
def config():
    return os.environ["REGION"], os.environ["STAGE"], os.environ["API_KEY"]

@app.function(secrets=[modal.Secret.from_name("billing-keys")])
def billing_key():
    return os.environ["BILLING_KEY"]

if __name__ == "__main__":
    modal.Secret.objects.create("billing-keys", {"BILLING_KEY": "sk-test"})
    with app.run():
        print(config.remote())
        print(billing_key.remote())
```

<!-- example: skip network -->
```bash
python3 settings.py
# -> ('eu', 'test', 'test-key')
# -> sk-test
```

A name holds one secret: creating a second under it raises `AlreadyExistsError`, and `modal secret create --force` replaces its values. A lookup that names `required_keys` raises `ConflictError` when the secret lacks one. On a class, `with_options(secrets=...)` replaces the variables the `@app.cls` decorator names. Save this as `rotate.py`:

```python
import os

import modal

app = modal.App("rotation")

@app.function(secrets=[modal.Secret.from_name("billing-keys")])
def billing_key():
    return os.environ["BILLING_KEY"]

@app.cls(secrets=[modal.Secret.from_dict({"TIER": "free", "REGION": "eu"})])
class Plan:
    @modal.method()
    def variables(self):
        return os.environ.get("TIER"), os.environ.get("REGION")

if __name__ == "__main__":
    try:
        modal.Secret.objects.create("billing-keys", {"BILLING_KEY": "sk-second"})
    except modal.exception.AlreadyExistsError as exc:
        print(type(exc).__name__)
    try:
        modal.Secret.from_name("billing-keys", required_keys=["WEBHOOK_KEY"]).hydrate()
    except Exception as exc:
        print(type(exc).__name__, exc)
    with app.run():
        print(billing_key.remote())
        print(Plan().variables.remote())
        paid = Plan.with_options(secrets=[modal.Secret.from_dict({"TIER": "paid"})])
        print(paid().variables.remote())
```

<!-- example: skip network -->
```bash
modal secret create --force billing-keys BILLING_KEY=sk-rotated | grep Created
# -> Created a new secret 'billing-keys' with the key 'BILLING_KEY'
python3 rotate.py
# -> AlreadyExistsError
# -> ConflictError Secret is missing key(s): WEBHOOK_KEY
# -> sk-rotated
# -> ('free', 'eu')
# -> ('paid', None)
```

## See what a function prints

Inside `modal.enable_output()` the SDK shows what each function the app runs printed. Save this as `logs.py`:

```python
import modal

app = modal.App("logs")

@app.function()
def speak():
    print("out one")
    print("out two")
    return "done"

@app.function()
def shout():
    print("from a second function")
    return "done too"

if __name__ == "__main__":
    with modal.enable_output():
        with app.run():
            results = speak.remote(), shout.remote()
    print(results)
```

<!-- example: skip network -->
```bash
python3 logs.py 2> logs.err
# -> ✓ Initialized. View run at ...
# -> ✓ Created objects.
# -> ├── ✓ Uploaded .../logs.py
# -> ├── ✓ Created Function speak.
# -> └── ✓ Created Function shout.
# -> out one
# -> out two
# -> from a second function
# -> ✓ App completed. View run at ...
# -> ('done', 'done too')
grep -o "Timed out waiting for final app logs." logs.err
# -> Timed out waiting for final app logs.
```

The first ten lines are standard output. The lines with a check mark are the SDK's own progress, and `...` stands for the run's URL and for the folder you saved the file in.

The last two of them arrive about 10 seconds after the calls, because the block takes that long to end. As it ends, the SDK logs the `Timed out` line to standard error, which the example keeps in `logs.err`.

## Call a deployed function by name

Deploy the app, then look a function up from other code with `modal.Function.from_name`. Save this as `call_deployed.py`:

```python
import modal

total = modal.Function.from_name("orders", "total")
print(total.remote([5, 5]))
try:
    print(modal.Function.from_name("orders", "refund").remote(1))
except modal.exception.NotFoundError as exc:
    print(type(exc).__name__)
```

<!-- example: skip network -->
```bash
modal deploy orders.py > /dev/null
python3 call_deployed.py
# -> 10.0
# -> NotFoundError
```

## Deploy a name again

A second deploy of a name replaces what the name serves: a call by name then runs the new code, and a function the new code adds is found. Replace `orders.py` with this:

```python
import modal

app = modal.App("orders")

@app.function()
def total(prices, tax=0.0):
    return round(sum(prices) * (1 + tax), 2) + 0.01

@app.function()
def refund(amount):
    return -amount
```

<!-- example: skip network -->
```bash
modal deploy orders.py > /dev/null
python3 call_deployed.py
# -> 10.01
# -> -1
```

**Differs from Modal:** the first call after a second deploy already runs the new code. On Modal a container of the earlier deploy can still take it.

## Stop a deployed app

`modal.App.lookup(name).stop()` ends the app's running calls, and the app takes no call after it. Save this as `worker.py`:

```python
import time

import modal

app = modal.App("worker")

@app.function(timeout=120)
def nap(seconds):
    time.sleep(seconds)
    return "rested"
```

Save this as `stop_check.py`. It stops the app while one call runs:

```python
import time

import modal

nap = modal.Function.from_name("worker", "nap")
running = nap.spawn(60)
time.sleep(1)
modal.App.lookup("worker").stop()

by_name = modal.Function.from_name("worker", "nap")
for call in (lambda: running.get(timeout=15), lambda: nap.remote(0), lambda: nap.spawn(0), lambda: by_name.remote(0)):
    try:
        print(call())
    except Exception as exc:
        print(type(exc).__name__)
```

<!-- example: skip network -->
```bash
modal deploy worker.py > /dev/null
python3 stop_check.py
# -> RemoteError
# -> ConflictError
# -> ConflictError
# -> NotFoundError
modal deploy worker.py > /dev/null
python3 -c 'import modal; print(modal.Function.from_name("worker", "nap").remote(0))'
# -> rested
```

| After the stop | The SDK raises |
|---|---|
| A call that was running | `RemoteError` |
| A call or a spawn on a handle from before the stop | `ConflictError` |
| A lookup of the app's function by name | `NotFoundError` |

The first four lines are in the table's order, with the handle's call before its spawn. Deploying the name again serves it again, as the last line shows.

## Test a call that fails

An exception your function raises is raised in the caller with its type and message, and `map` returns it in place of a result when you pass `return_exceptions=True`. Save this as `charge.py`:

```python
import modal

app = modal.App("billing")

@app.function()
def charge(amount):
    if amount <= 0:
        raise ValueError("amount must be positive")
    return amount

if __name__ == "__main__":
    with app.run():
        try:
            charge.remote(0)
        except ValueError as exc:
            print(type(exc).__name__, exc)
        results = charge.map([5, 0], return_exceptions=True)
        print([type(result).__name__ for result in results])
```

<!-- example: skip network -->
```bash
python3 charge.py
# -> ValueError amount must be positive
# -> ['int', 'ValueError']
```

## Call a class's methods

A class defined with `@app.cls` keeps its state between calls on one instance, as on Modal. Save this as `counter.py`:

```python
import modal

app = modal.App("counters")

@app.cls()
class Counter:
    start: int = modal.parameter(default=0)

    @modal.enter()
    def begin(self):
        self.total = self.start

    @modal.method()
    def add(self, n):
        self.total += n
        return self.total

if __name__ == "__main__":
    with app.run():
        counter = Counter(start=5)
        print(counter.add.remote(1), counter.add.remote(2))
```

<!-- example: skip network -->
```bash
python3 counter.py
# -> 6 8
```

To call a deployed class from other code, look it up with `modal.Cls.from_name`: its parameters and methods work as they do on the class itself. Save this as `call_class.py`:

```python
import modal

Counter = modal.Cls.from_name("counters", "Counter")
counter = Counter(start=5)
print(counter.add.remote(1), counter.add.remote(2))
try:
    modal.Cls.from_name("counters", "Missing")().add.remote(1)
except modal.exception.NotFoundError as exc:
    print(type(exc).__name__)
```

<!-- example: skip network -->
```bash
modal deploy counter.py > /dev/null
python3 call_class.py
# -> 6 8
# -> NotFoundError
```

## Send many calls at once

Calls sent together, by `map` or by several `spawn` calls, are shared among several containers: as many as the function's `max_containers` allows. Save this as `batch.py`:

```python
import os
import time

import modal

app = modal.App("batch")

@app.function(max_containers=2)
def render(page):
    time.sleep(2)
    return os.environ["MODAL_TASK_ID"]

if __name__ == "__main__":
    with app.run():
        print(len(set(render.map(range(4)))))
```

<!-- example: skip network -->
```bash
python3 batch.py
# -> 2
```

**Differs from Modal:** a function with no `max_containers` runs in at most 16 containers at once, the simulator's limit on running commands, which [The Python your code runs on](https://www.rystic.ai/docs/simulators/modal/features/python-runtime.md) says how to raise. Modal starts more.

## Run a function on a schedule

A deployed function with `schedule=` runs on the simulator's clock, and nothing runs at the deploy. Moving the clock past a due time runs the function once for each `modal.Period` or `modal.Cron` time that came due. The runs start when the move ends: right after it they are queued, and they finish within seconds. `modal.App.lookup(name).stop()` ends the schedule. Save this as `nightly.py`:

```python
import modal

app = modal.App("nightly")

@app.function(schedule=modal.Period(minutes=5))
def report():
    modal.Queue.from_name("nightly-runs", create_if_missing=True).put("ran")
```

Save this as `schedule_check.py`. It moves the clock 630 seconds, past two due times, then stops the app and moves it again:

```python
import json
import os
import time
import urllib.request

import modal

def advance(seconds):
    body = json.dumps({"advance_seconds": seconds}).encode()
    request = urllib.request.Request(os.environ["RYSTIC_URL"] + "/_rystic/clock", data=body, headers={"Content-Type": "application/json"})
    urllib.request.urlopen(request).close()

runs = modal.Queue.from_name("nightly-runs", create_if_missing=True)
print(runs.len())

advance(630)
print([runs.get(timeout=30) for _ in range(2)], runs.len())

modal.App.lookup("nightly").stop()
advance(630)
time.sleep(3)
print(runs.len())
```

<!-- example: skip network -->
```bash
modal deploy nightly.py > /dev/null
python3 schedule_check.py
# -> 0
# -> ['ran', 'ran'] 0
# -> 0
```

One clock move runs a function at most 100 times and skips the rest. A cron line outside the simulator's dialect is accepted and never runs, and nothing says so at the deploy. The dialect is five fields with lists, ranges, steps and names: `@daily`, a six-field line and `L` are outside it. Save this as `cron_lines.py`:

```python
import modal

app = modal.App("cron-lines")

@app.function(schedule=modal.Cron("@daily"))
def unread():
    modal.Queue.from_name("cron-runs", create_if_missing=True).put("unread")

@app.function(schedule=modal.Period(minutes=1))
def steady():
    modal.Queue.from_name("cron-runs", create_if_missing=True).put("steady")
```

Save this as `limits_check.py`. It moves the clock a day and 30 seconds, past 1,440 due times of the one-minute function:

```python
import json
import os
import time
import urllib.request

import modal

body = json.dumps({"advance_seconds": 86430}).encode()
request = urllib.request.Request(os.environ["RYSTIC_URL"] + "/_rystic/clock", data=body, headers={"Content-Type": "application/json"})
urllib.request.urlopen(request).close()

runs = modal.Queue.from_name("cron-runs", create_if_missing=True)
seen = []
while len(seen) < 100:
    seen += runs.get_many(100, timeout=30)
time.sleep(3)
print(len(seen), sorted(set(seen)), runs.len())
```

<!-- example: skip network -->
```bash
modal deploy cron_lines.py > /dev/null
python3 limits_check.py
# -> 100 ['steady'] 0
```

**Differs from Modal:** a schedule follows the simulator's clock, which moves only when a test moves it. The simulator keeps no call record of a scheduled run, so a client cannot look one up. A period's due times sit at the deploy's own instant plus whole periods. A move that ends exactly on one may or may not reach that run, so move a little past it, as the 630 seconds above do. Whether Modal runs a cron line outside this dialect, and what it shows a client for a scheduled run, are not measured.

## What a call runs on

| | On the simulator |
|---|---|
| Where your code runs | In a process on the simulator's machine, which must be Linux |
| Its Python | The simulator's, with the `modal` package: the one in its Docker image, or the one you name |
| Your module | The source the SDK uploads when the app runs or deploys |
| The function's image | Accepted and not built, as [Sandboxes](https://www.rystic.ai/docs/simulators/modal/features/sandboxes.md) shows for a sandbox, so an import your function needs comes from the simulator's Python |

**Differs from Modal:** no image is built, and no call runs on a GPU.

[Limitations](https://www.rystic.ai/docs/simulators/modal.md#limitations) lists the calls that do not work, generators and web endpoints among them.

---

Source: https://www.rystic.ai/docs/simulators/modal/features/functions · Markdown: https://www.rystic.ai/docs/simulators/modal/features/functions.md
