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, which includes other Modal objects.

Lifetime of a Dict and its items

An individual dict entry will expire 30 days after it was last added to its Dict object. Additionally, data are stored in memory on the Modal server and could be lost due to unexpected server restarts. Because of this, Dict is best suited for storing short-term state and is not recommended for durable storage.

Usage

from modal import Dict

my_dict = Dict.from_name("my-persisted_dict", create_if_missing=True)

my_dict["some key"] = "some value"
my_dict[123] = 456

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

The Dict class offers a few methods for operations that are usually accomplished in Python with operators, such as Dict.put and Dict.contains. The advantage of these methods is that they can be safely called in an asynchronous context, whereas their operator-based analogues will block the event loop.

For more examples, see the guide.

new

@staticmethod
def new(data: Optional[dict] = None):

Dict.new is deprecated.

Please use Dict.from_name (for persisted) or Dict.ephemeral (for ephemeral) dicts.

ephemeral

@classmethod
@contextmanager
def ephemeral(
    cls: Type["_Dict"],
    data: Optional[dict] = None,
    client: Optional[_Client] = None,
    environment_name: Optional[str] = None,
    _heartbeat_sleep: float = EPHEMERAL_OBJECT_HEARTBEAT_SLEEP,
) -> Iterator["_Dict"]:

Creates a new ephemeral dict within a context manager:

Usage:

from modal import Dict

with Dict.ephemeral() as d:
    d["foo"] = "bar"

async with Dict.ephemeral() as d:
    await d.put.aio("foo", "bar")

from_name

@staticmethod
def from_name(
    label: str,
    data: Optional[dict] = None,
    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

from modal import Dict

dict = Dict.from_name("my-dict", create_if_missing=True)
dict[123] = 456

persisted

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

Deprecated! Use Dict.from_name(name, create_if_missing=True).

lookup

@staticmethod
def lookup(
    label: str,
    data: Optional[dict] = None,
    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.

from modal import Dict

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

delete

@staticmethod
def delete(
    label: str,
    *,
    client: Optional[_Client] = None,
    environment_name: Optional[str] = None,
):

clear

@live_method
def clear(self) -> None:

Remove all items from the 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.

keys

@live_method_gen
def keys(self) -> Iterator[Any]:

Return an iterator over the keys in this dictionary.

Note that (unlike with Python dicts) the return value is a simple iterator, and results are unordered.

values

@live_method_gen
def values(self) -> Iterator[Any]:

Return an iterator over the values in this dictionary.

Note that (unlike with Python dicts) the return value is a simple iterator, and results are unordered.

items

@live_method_gen
def items(self) -> Iterator[Tuple[Any, Any]]:

Return an iterator over the (key, value) tuples in this dictionary.

Note that (unlike with Python dicts) the return value is a simple iterator, and results are unordered.