trycast supports TypedDict plus most types you’d expect to see in a JSON-serializable structure, however it does not currently support checking Protocols, which seems to be what you want.
IIRC isinstance can check certain kinds of Protocols itself (but not all of them). See if isinstance(value, MyProtocol) works by itself for your case, at runtime.
If it does work, then you probably can write a function similar to:
P = TypeVar('P', bound=Protocol)
def as_protocol(obj: object, proto: type[P]) -> P | None:
return obj if isinstance(obj, proto) else None
I rarely use Protocols myself, so I’m not 100% sure the above code works.
@davidfstr I don’t want to derail the thread so I’ll tag you in the previous topic I mentioned where this all situation started - feel free to ignore it if it’s not of your interest.
Short answer is: at runtime, isinstance at runtime does work, but it’s not making mypy happy because it does not consider MyProtocol a concrete class which is the only use case it seems to accept unless I disable the error code type-abstract, but I don’t know if this is safe or not.