
Agreed on making the plugin define a TypedDict of their own as opposed to the monkey-patching approach. I guess an issue with the TypedDict approach is that we are potentially lying that all or some of the keys on the TypedDict are required. Can we improve on this approach without the cast? Perhaps we can advise plugins to set total=False when using it with Item[T], but there isn't a way to enforce that AFAIK? Still a disadvantage of this is that we lose the namespace isolation by sharing the same dict of string keys. On Fri, Aug 18, 2023 at 4:38 PM Thomas Kehrenberg <tmke8@posteo.net> wrote:
Why not something like:
from typing import Any, Generic, Mapping, TypeVar, TypedDict, cast
T = TypeVar("T", bound=Mapping[str, Any])
class Item(Generic[T]): def __init__(self) -> None: self.stash: T = cast(T, {})
class MyStash(TypedDict): my_plugin_attr: int
def pytest_runtest_setup(item: Item[MyStash]) -> None: item.stash["my_plugin_attr"] = 8
def pytest_runtest_teardown(item: Item[MyStash]) -> None: print(item.stash["my_plugin_attr"]) # Maybe del item.stash["my_plugin_attr"] # type error here because the key is required
This works in both pyright and mypy. _______________________________________________ Typing-sig mailing list -- typing-sig@python.org To unsubscribe send an email to typing-sig-leave@python.org