modal.dict

modal.dict.Dict

class Dict(modal.object.Provider)

A distributed dictionary available to Modal apps.

Keys and values can be essentially any object, so long as it can be serialized by cloudpickle, including Modal objects.

Lifetime of dictionary and its items

A Dict’s lifetime matches the lifetime of the app it’s attached to, but invididual keys expire after 30 days. Because of this, Dicts are best used as a cache and not relied on for persistent storage. On app completion or after stopping an app any associated Dict objects are cleaned up.

Usage

This is the constructor object, used only to attach a DictHandle to an app. To interact with Dict contents, use DictHandle objects that are attached to the live app once an app is running.

import modal

stub = modal.Stub()
stub.some_dict = modal.Dict()
# stub.some_dict["message"] = "hello world" # TypeError!

if __name__ == "__main__":
    with stub.run() as app:
        handle = app.some_dict
        handle["message"] = "hello world"  # OK ✔️
def __init__(self, data={}):

Create a new dictionary, optionally filled with initial data.

persist

@typechecked
def persist(self, label: str, namespace=api_pb2.DEPLOYMENT_NAMESPACE_WORKSPACE):

Deploy a Modal app containing this object. This object can then be imported from other apps using the returned reference, or by calling modal.SharedVolume.from_name(label) (or the equivalent method on respective class).

Example Usage

import modal

volume = modal.SharedVolume().persist("my-volume")

stub = modal.Stub()

# Volume refers to the same object, even across instances of `stub`.
@stub.function(shared_volumes={"/vol": volume})
def f():
    pass

from_name

@classmethod
def from_name(
    cls: Type[P],
    app_name: str,
    tag: Optional[str] = None,
    namespace=api_pb2.DEPLOYMENT_NAMESPACE_WORKSPACE,
) -> P:

Returns a reference to an Modal object of any type

Useful for referring to already created/deployed objects, e.g., Secrets

import modal

stub = modal.Stub()

@stub.function(secret=modal.Secret.from_name("my-secret-name"))
def some_function():
    pass

lookup

@classmethod
def lookup(
    cls: Type[P],
    app_name: str,
    tag: Optional[str] = None,
    namespace=api_pb2.DEPLOYMENT_NAMESPACE_WORKSPACE,
    client: Optional[_Client] = None,
) -> H:

General purpose method to retrieve Modal objects such as functions, shared volumes, and secrets.

import modal
square = modal.Function.lookup("my-shared-app", "square")
assert square(3) == 9
vol = modal.SharedVolume.lookup("my-shared-volume")
for chunk in vol.read_file("my_db_dump.csv"):
    ...

modal.dict.DictHandle

class DictHandle(modal.object.Handle)

Handle for interacting with the contents of a Dict

stub.some_dict = modal.Dict()

if __name__ == "__main__":
    with stub.run() as app:
        app.some_dict["message"] = "hello world"
def __init__(self):

is_hydrated

def is_hydrated(self) -> bool:
    # A hydrated Handle is fully functional and linked to a live object in an app
    # To hydrate Handles, run an app using stub.run() or look up the object from a running app using <HandleClass>.lookup()

from_id

@classmethod
def from_id(cls: Type[H], object_id: str, client: Optional[_Client] = None) -> H:

Get an object of this type from a unique object id (retrieved from obj.object_id)

object_id

@property
def object_id(self) -> str:

A unique object id for this instance. Can be used to retrieve the object using .from_id()

from_app

@classmethod
def from_app(
    cls: Type[H],
    app_name: str,
    tag: Optional[str] = None,
    namespace=api_pb2.DEPLOYMENT_NAMESPACE_WORKSPACE,
    client: Optional[_Client] = None,
) -> H:

Returns a handle to a tagged object in a deployment on Modal.

get

def get(self, key: Any) -> Any:

Get the value associated with the key.

Raises KeyError if the key does not exist.

contains

def contains(self, key: Any) -> bool:

Check if the key exists.

len

def len(self) -> int:

Returns the length of the dictionary, including any expired keys.

update

def update(self, **kwargs) -> None:

Update the dictionary with additional items.

put

def put(self, key: Any, value: Any) -> None:

Add a specific key-value pair in the dictionary.

pop

def pop(self, key: Any) -> Any:

Remove a key from the dictionary, returning the value if it exists.