Skip to content

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

@jorenham

Description

@jorenham

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"

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions