r"""``Stash`` is a type-safe heterogeneous mutable mapping that allows keys and value types to be defined separately from where it (the ``Stash``) is created. Usually you will be given an object which has a ``Stash``, for example :class:`~pytest.Config` or a :class:`~_pytest.nodes.N
| 27 | |
| 28 | |
| 29 | class Stash: |
| 30 | rclass="st">"""``Stash`` is a type-safe heterogeneous mutable mapping that |
| 31 | allows keys and value types to be defined separately from |
| 32 | where it (the ``Stash``) is created. |
| 33 | |
| 34 | Usually you will be given an object which has a ``Stash``, for example |
| 35 | :class:`~pytest.Config` or a :class:`~_pytest.nodes.Node`: |
| 36 | |
| 37 | .. code-block:: python |
| 38 | |
| 39 | stash: Stash = some_object.stash |
| 40 | |
| 41 | If a module or plugin wants to store data in this ``Stash``, it creates |
| 42 | :class:`StashKey`\s for its keys (at the module level): |
| 43 | |
| 44 | .. code-block:: python |
| 45 | |
| 46 | class="cm"># At the top-level of the module |
| 47 | some_str_key = StashKey[str]() |
| 48 | some_bool_key = StashKey[bool]() |
| 49 | |
| 50 | To store information: |
| 51 | |
| 52 | .. code-block:: python |
| 53 | |
| 54 | class="cm"># Value type must match the key. |
| 55 | stash[some_str_key] = class="st">"value" |
| 56 | stash[some_bool_key] = True |
| 57 | |
| 58 | To retrieve the information: |
| 59 | |
| 60 | .. code-block:: python |
| 61 | |
| 62 | class="cm"># The static type of some_str is str. |
| 63 | some_str = stash[some_str_key] |
| 64 | class="cm"># The static type of some_bool is bool. |
| 65 | some_bool = stash[some_bool_key] |
| 66 | |
| 67 | .. versionadded:: 7.0 |
| 68 | class="st">""" |
| 69 | |
| 70 | __slots__ = (class="st">"_storage",) |
| 71 | |
| 72 | def __init__(self) -> None: |
| 73 | self._storage: dict[StashKey[Any], object] = {} |
| 74 | |
| 75 | def __setitem__(self, key: StashKey[T], value: T) -> None: |
| 76 | class="st">""class="st">"Set a value for key."class="st">"" |
| 77 | self._storage[key] = value |
| 78 | |
| 79 | def __getitem__(self, key: StashKey[T]) -> T: |
| 80 | class="st">"""Get the value for key. |
| 81 | |
| 82 | Raises ``KeyError`` if the key wasn&class="cm">#x27;t set before. |
| 83 | class="st">""" |
| 84 | return cast(T, self._storage[key]) |
| 85 | |
| 86 | def get(self, key: StashKey[T], default: D) -> T | D: |
no outgoing calls