modal.dict

modal.dict.Dict

class Dict(modal.object.Object)

Distributed dictionary for storage in Modal apps.

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

Lifetime of a Dict and its items

A Dict matches the lifetime of the app it is attached to, but an individual entry will expire 30 days after it was last added to its Dict object. Because of this, Dicts are best not used for long-term storage. All data is deleted when the app is stopped.

Usage

Create a new Dict with Dict.new(), then assign it to a stub or function.

from modal import Dict, Stub

stub = Stub()
stub.my_dict = Dict.new()

@stub.local_entrypoint()
def main():
    stub.my_dict["some key"] = "some value"
    stub.my_dict[123] = 456

    assert stub.my_dict["some key"] == "some value"
    assert stub.my_dict[123] == 456

For more examples, see the guide.

new

@typechecked
@staticmethod
def new(data: Optional[dict] = None) -> "_Dict":

Create a new Dict, optionally with initial data.

from_name

@staticmethod
def from_name(
    label: str,
    namespace=api_pb2.DEPLOYMENT_NAMESPACE_WORKSPACE,
    environment_name: Optional[str] = None,
    create_if_missing: bool = False,
) -> "_Dict":

Create a reference to a persisted Dict

Examples

# In one app:
stub.dict = Dict.persisted("my-dict")

# Later, in another app or Python file:
stub.dict = Dict.from_name("my-dict")

persisted

@staticmethod
def persisted(
    label: str, namespace=api_pb2.DEPLOYMENT_NAMESPACE_WORKSPACE, environment_name: Optional[str] = None
) -> "_Dict":

Create a persisted modal.Dict which as a lifetime beyond the app it was created in. The object will persist until it is deleted by the user.

lookup

@staticmethod
def lookup(
    label: str,
    namespace=api_pb2.DEPLOYMENT_NAMESPACE_WORKSPACE,
    client: Optional[_Client] = None,
    environment_name: Optional[str] = None,
    create_if_missing: bool = False,
) -> "_Dict":

Lookup a dict with a given name and tag.

d = modal.Dict.lookup("my-dict")
d["xyz"] = 123

clear

@live_method
def clear(self) -> None:

Remove all items from the modal.Dict.

get

@live_method
def get(self, key: Any, default: Optional[Any] = None) -> Any:

Get the value associated with a key.

Returns default if key does not exist.

contains

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

Return if a key is present.

len

@live_method
def len(self) -> int:

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

update

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

Update the dictionary with additional items.

put

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

Add a specific key-value pair to the dictionary.

pop

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

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