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

Supports Type[T] type with delegate #316

Merged
merged 1 commit into from
Oct 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions tests/test_typeclass/test_typing_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from typing import Type

import pytest

from classes import typeclass


class _MyClass(object):
"""We use this class to test `Type[MyClass]`."""


class _MyClassTypeMeta(type):
def __instancecheck__(cls, typ) -> bool:
return typ is _MyClass


class _MyClassType(Type[_MyClass], metaclass=_MyClassTypeMeta): # type: ignore
"""Delegate class."""


@typeclass
def class_type(typ) -> Type:
"""Returns the type representation."""


@class_type.instance(delegate=_MyClassType)
def _my_class_type(typ: Type[_MyClass]) -> Type:
return typ


def test_correct_class_type():
"""Ensures `Type[T]` works correctly with delegate."""
assert class_type(_MyClass) is _MyClass


@pytest.mark.parametrize('typ', [
int, float, type, dict, list,
])
def test_wrong_class_type(typ):
"""Ensures other types doesn't works with our delegate."""
with pytest.raises(NotImplementedError):
class_type(typ)


def test_passing_class_type_instance():
"""Ensures passing a instance of the expected type doesn't work."""
with pytest.raises(NotImplementedError):
class_type(_MyClass()) # type: ignore[arg-type]
26 changes: 26 additions & 0 deletions typesafety/test_typing_type.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
- case: typing_type_correct
disable_cache: true
main: |
from typing import Type
from classes import typeclass

class _MyClass(object):
...

class _MyClassType(Type[_MyClass]):
...


@typeclass
def class_type(typ) -> Type:
...

@class_type.instance(delegate=_MyClassType)
def _my_class_type(typ: Type[_MyClass]) -> Type:
return typ

class_type(_MyClass)
class_type(int)
out: |
main:7: error: Invalid base class "Type"
main:20: error: Argument 1 to "class_type" has incompatible type "Type[int]"; expected "Type[_MyClass]"