Skip to Content
SimulatorsModalDicts and queues

Simulators

Dicts and queues

To test code that passes data through modal.Dict and modal.Queue, create them by name and use them from your test and from your functions: both see the same object. Save this as shared.py:

import modal

app = modal.App("shared")


@app.function()
def work(n):
    jobs = modal.Queue.from_name("jobs")
    totals = modal.Dict.from_name("totals", create_if_missing=True)
    item = jobs.get(timeout=10)
    totals[item] = totals.get(item, 0) + n
    return jobs.len()


if __name__ == "__main__":
    jobs = modal.Queue.from_name("jobs", create_if_missing=True)
    totals = modal.Dict.from_name("totals", create_if_missing=True)
    jobs.put_many(["a", "b", "a"])
    with app.run():
        print([work.remote(n) for n in (1, 2, 3)])
    print(sorted(totals.items()), jobs.get(block=False))

Put the modal version that The Python your code runs on names in place of <version>, point the SDK at the simulator and run the file:

pip install -q "modal==<version>"
export MODAL_SERVER_URL="$RYSTIC_URL" MODAL_TOKEN_ID=ak-example MODAL_TOKEN_SECRET=as-example
python3 shared.py
# -> [2, 1, 0]
# -> [('a', 4), ('b', 2)] None

Read, change and delete them

A dict takes update, get with a default, in, len and pop. A queue keeps each partition apart, returns None from an empty get(block=False) and raises queue.Empty when a timeout passes. modal.Dict.ephemeral() and modal.Queue.ephemeral() make one with no name, and objects.delete removes a named one. Save this as objects.py:

import queue

import modal

d = modal.Dict.from_name("settings", create_if_missing=True)
d.update({"region": "eu"}, retries=3)
print(d["region"], d.get("missing", "none"), "retries" in d, d.len())
print(d.pop("retries"), sorted(d.keys()))

q = modal.Queue.from_name("events", create_if_missing=True)
q.put("default")
q.put_many(["a1", "a2"], partition="tenant-a")
print(q.len(), q.len(partition="tenant-a"), q.len(total=True))
print(q.get_many(5, partition="tenant-a", block=False), q.get())
try:
    q.get(timeout=1)
except queue.Empty:
    print("Empty")

with modal.Dict.ephemeral() as scratch:
    scratch["k"] = "v"
    print(scratch["k"])

modal.Dict.objects.delete("settings")
modal.Queue.objects.delete("events")
try:
    modal.Dict.from_name("settings").hydrate()
except modal.exception.NotFoundError as exc:
    print(type(exc).__name__)
python3 objects.py
# -> eu none True 2
# -> 3 ['region']
# -> 1 2 3
# -> ['a1', 'a2'] default
# -> Empty
# -> v
# -> NotFoundError

List them

modal.Dict.objects.list() and modal.Queue.objects.list() return the named ones, newest first, and max_objects keeps the newest. Save this as listing.py:

import modal

for name in ("flags", "limits"):
    modal.Dict.from_name(name, create_if_missing=True).hydrate()
modal.Queue.from_name("retries", create_if_missing=True).hydrate()

print([d.name for d in modal.Dict.objects.list()])
print([d.name for d in modal.Dict.objects.list(max_objects=2)])
print([q.name for q in modal.Queue.objects.list()])
with modal.Dict.ephemeral():
    print(len(modal.Dict.objects.list()))
python3 listing.py
# -> ['limits', 'flags', 'totals']
# -> ['limits', 'flags']
# -> ['retries', 'jobs']
# -> 3

The lists also include totals and jobs, which the first example made. A dict with no name is not listed: the last line counts three while one is open.

Last updated on