Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

an alternative to @runtime_checkable that accepts a user-defined type-guard #252

Open
jorenham opened this issue Jan 14, 2025 · 0 comments

Comments

@jorenham
Copy link
Owner

jorenham commented Jan 14, 2025

Should be implemented as metaclass, not a decorator (mypy still fails to understand class decorators).

It could, for example, look like this:

from typing import Literal, Protocol, TypeIs
from optype.typing import ProtoType

class HasSpam(Protocol, metaclass=ProtoType):
    spam: ClassVar[Literal["spam"]]


@HasSpam.on_isinstance
def type_has_spam(obj: object, /) -> TypeIs[HasSpam]:
	return getattr(type(obj), "spam", None) == "spam"

@HasSpam.on_issubclass
def has_spam(tp: object, /) -> TypeIs[type[HasSpam]]:
	return isinstance(obj, type) and getattr(obj, "spam", None) == "spam"
@jorenham jorenham changed the title an alternative to @runtime_checkable that accepts a user-defined -> TypeIs[T] type-guard an alternative to @runtime_checkable that accepts a user-defined type-guard Jan 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant