stash.py
Overview
The [stash.py](/projects/286/67434) file implements a type-safe, heterogeneous mutable mapping system called `Stash` and a key representation class `StashKey` used to index values within the `Stash`. The main purpose of this file is to provide a utility that allows storing and retrieving values of different types in a single shared container without compromising type safety.
This is particularly useful in modular or plugin-based systems where different modules may want to store data in a common object without risking key collisions or type mismatches. Each key (`StashKey`) is unique and associated with a specific value type, ensuring that values retrieved from the `Stash` match the expected type.
The file is designed with static type checking in mind, leveraging Python generics and typing hints to enforce and document the expected types of keys and values.
Classes
StashKey[T]
A generic key type used to index values of type `T` in a `Stash`.
Purpose:
Acts as a strongly-typed, unique key to store and retrieve values in aStash. EachStashKeyinstance corresponds to a single typeT.Type Parameter:
T: The type of the value associated with this key.
Characteristics:
Uniqueness: Each instance is unique and cannot conflict with any other key.
Uses
__slots__to avoid per-instance dictionaries, indicating no instance attributes are stored.
Usage Example:
from stash import StashKey # Declare keys at module level user_name_key = StashKey[str]() active_key = StashKey[bool]()Notes:
This class contains no methods or attributes beyond what is inherited fromGeneric. Its main role is as a typed identifier.
Stash
A type-safe, heterogeneous mutable mapping that allows storing and retrieving values of arbitrary types keyed by `StashKey`s.
Purpose:
To provide a centralized storage container where modules or plugins can store data under type-safe keys, without requiring that all keys or values are known upfront.Internal Storage:
Uses a private dictionary_storagemapping fromStashKey[Any]toobject.Slots:
Uses__slots__ = ("_storage",)for memory efficiency.
Methods
__init__(self) -> None
Initializes an empty
Stash.Creates an empty dictionary
_storageto hold key-value pairs.
__setitem__(self, key: StashKey[T], value: T) -> None
Sets the value associated with the given
key.Parameters:
key: AStashKeyinstance parameterized by typeT.value: The value of typeTto associate withkey.
Usage:
stash[some_key] = some_value
__getitem__(self, key: StashKey[T]) -> T
Retrieves the value associated with the given
key.Parameters:
key: AStashKeyinstance parameterized by typeT.
Returns:
The value of type
Tassociated withkey.
Raises:
KeyErrorif thekeyis not present in the stash.
Usage:
value = stash[some_key]
get(self, key: StashKey[T], default: D) -> T | D
Retrieves the value for
keyif present; otherwise returnsdefault.Parameters:
key: AStashKeyinstance parameterized by typeT.default: A value of typeDto return ifkeyis not found.
Returns:
Value of type
Tassociated withkey, ordefaultof typeD.
Usage:
value = stash.get(some_key, default_value)
setdefault(self, key: StashKey[T], default: T) -> T
Returns the value associated with
keyif it exists; otherwise, setskeytodefaultand returnsdefault.Parameters:
key: AStashKeyof typeT.default: Value of typeTto set and return ifkeyis missing.
Returns:
The existing or newly set value of type
T.
Usage:
value = stash.setdefault(some_key, default_value)
__delitem__(self, key: StashKey[T]) -> None
Deletes the value associated with
key.Parameters:
key: AStashKeyinstance.
Raises:
KeyErrorifkeyis not present.
Usage:
del stash[some_key]
__contains__(self, key: StashKey[T]) -> bool
Checks if
keyis present in the stash.Parameters:
key: AStashKeyinstance.
Returns:
Trueifkeyexists, elseFalse.
Usage:
if some_key in stash: ...
__len__(self) -> int
Returns the number of items stored in the stash.
Usage:
count = len(stash)
Implementation Details
Type Safety via Generics:
The use ofGenericandTypeVarenforces that each key is associated with a single corresponding value type, which is preserved throughout storage and retrieval. This improves static type checking and reduces runtime errors.Uniqueness of Keys:
EachStashKeyinstance is unique, so there is no risk of key collision between different modules or plugins even if the keys have the same type parameter.Storage as Dictionary:
Internally, the stash uses a standard Python dictionary with keys asStashKey[Any]and values asobject. Casting is used when retrieving to ensure type correctness.Memory Optimization:
BothStashKeyandStashuse__slots__to reduce memory overhead by preventing the creation of instance dictionaries.
Interaction with Other System Components
Intended Usage Context:
Stashis designed as a utility to be embedded as an attribute (commonly named.stash) on other objects within the system, such as configuration objects (Config) or nodes (Node) in a tree structure.Plugin and Module Data Storage:
Plugins or modules createStashKeyinstances at their module level to define typed keys, then use these keys to store and retrieve data in a sharedStash. This pattern allows decoupled components to share data safely.Decoupling and Extensibility:
By separating key definition from storage and retrieval, theStashprovides a flexible extension point for different parts of the system to communicate without tight coupling.
Usage Example
from stash import Stash, StashKey
# Module-level keys
user_id_key = StashKey[int]()
logged_in_key = StashKey[bool]()
# Creating a stash instance (usually provided by some system component)
stash = Stash()
# Storing values
stash[user_id_key] = 1234
stash[logged_in_key] = True
# Retrieving values
user_id: int = stash[user_id_key]
is_logged_in: bool = stash.get(logged_in_key, False)
# Checking existence
if user_id_key in stash:
print(f"User ID is {stash[user_id_key]}")
# Using setdefault
default_user = stash.setdefault(user_id_key, 0)
Mermaid Class Diagram
classDiagram
class StashKey~T~ {
<<generic>>
}
class Stash {
-_storage: dict[StashKey[Any], object]
+__init__()
+__setitem__(key: StashKey[T], value: T)
+__getitem__(key: StashKey[T]) T
+get(key: StashKey[T], default: D) T|D
+setdefault(key: StashKey[T], default: T) T
+__delitem__(key: StashKey[T])
+__contains__(key: StashKey[T]) bool
+__len__() int
}
Summary
The [stash.py](/projects/286/67434) file offers a simple yet powerful mechanism to store and retrieve heterogeneously typed values with strong type safety guarantees, facilitating modular, decoupled data sharing inside larger systems or frameworks. Its design ensures that keys are unique and strongly typed, preventing runtime errors and simplifying static analysis. This makes it ideal for plugin architectures and complex applications needing a flexible shared state container.