Skip to content

Commit

Permalink
add issubform support for Never and ban instanciating it at runtime
Browse files Browse the repository at this point in the history
  • Loading branch information
DetachHead committed Jan 7, 2022
1 parent b1956f6 commit 54d645e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
18 changes: 14 additions & 4 deletions basedtyping/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
Sequence,
TypeVar,
_GenericAlias,
_SpecialForm,
cast,
)

Expand All @@ -26,6 +27,7 @@
"""

Never = NoReturn
"""a type that can never exist. this is the narrowest possible type"""
else:
# for isinstance checks
Function = Callable
Expand All @@ -34,6 +36,9 @@ class _NeverMetaclass(type):
def __instancecheck__(cls, instance: object) -> bool:
return False

def __call__(cls) -> Never:
raise TypeError("cannot instanciate Never")

class Never(metaclass=_NeverMetaclass):
pass

Expand Down Expand Up @@ -223,8 +228,10 @@ def __class_getitem__(cls, item) -> type[ReifiedGeneric[T]]:

# TODO: make this work with any "form", not just unions
# should be (form: TypeForm, forminfo: TypeForm)
def issubform(form: type | UnionType, forminfo: type | UnionType) -> bool:
"""EXPERIMENTAL: Warning, this function currently only supports unions.
def issubform(
form: type | UnionType | _SpecialForm, forminfo: type | UnionType | _SpecialForm
) -> bool:
"""EXPERIMENTAL: Warning, this function currently only supports unions and ``Never``.
Returns ``True`` if ``form`` is a subform (specialform or subclass) of ``forminfo``.
Expand All @@ -241,9 +248,12 @@ def issubform(form: type | UnionType, forminfo: type | UnionType) -> bool:
>>> issubform(int | str, object)
True
"""
# type ignores because issubclass doesn't support _SpecialForm but we do
if isinstance(form, UnionType | OldUnionType):
for t in cast(Sequence[type], cast(UnionType, form).__args__):
if not issubclass(t, forminfo):
if not issubform(t, forminfo):
return False
return True
return issubclass(form, forminfo)
if form is Never:
return True
return issubclass(form, forminfo) # type:ignore[arg-type]
17 changes: 16 additions & 1 deletion tests/test_never_type/test_runtime.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from basedtyping import Never
from pytest import raises

from basedtyping import Never, issubform


def test_isinstance() -> None:
Expand All @@ -7,3 +9,16 @@ def test_isinstance() -> None:
# https://github.com/KotlinIsland/basedmypy/issues/136
Never, # type:ignore[arg-type]
)


def test_issubform_true() -> None:
assert issubform(Never, int)


def test_issubform_false() -> None:
assert not issubform(str, Never)


def test_cant_instanciate() -> None:
with raises(TypeError):
Never() # type:ignore[operator]

0 comments on commit 54d645e

Please sign in to comment.