Skip to content

Commit

Permalink
Bugfix in dispatch: Now supports dispatch on user generics, by discar…
Browse files Browse the repository at this point in the history
…ding the generic parameters
  • Loading branch information
erezsh committed Sep 13, 2024
1 parent 4a7daca commit 2b9fa73
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
5 changes: 3 additions & 2 deletions runtype/pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ def _to_canon(self, t):
return Tuple
if Ellipsis in args:
if len(args) != 2 or args[0] == Ellipsis:
raise ValueError("Tuple with '...'' expected to be of the exact form: tuple[t, ...].")
raise ValueError("Tuple with '...' expected to be of the exact form: tuple[t, ...].")
return TupleEllipsis[to_canon(args[0])]

return ProductType([to_canon(x) for x in args])
Expand All @@ -584,7 +584,6 @@ def _to_canon(self, t):
return SumType(res)
elif origin is abc.Callable or origin is typing.Callable:
return Callable[ProductType(to_canon(x) for x in args[:-1]), to_canon(args[-1])]
return Callable # TODO
elif origin is typing.Literal:
return OneOf(args)
elif origin is abc.Mapping or origin is typing.Mapping:
Expand All @@ -611,6 +610,8 @@ def _to_canon(self, t):
return Type[self.to_canon(t)]
# TODO test issubclass on t.__args__
return Type
elif isinstance(t, typing._GenericAlias):
return self._to_canon(origin)

raise NotImplementedError("No support for type:", t)

Expand Down
13 changes: 12 additions & 1 deletion tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import sys

import typing
from typing import Any, List, Dict, Tuple, Union, Optional, Callable, Set, FrozenSet, Sequence, Type
from typing import Any, List, Dict, Tuple, Union, Optional, Callable, Set, FrozenSet, Sequence, Type, TypeVar, Generic
from collections.abc import Iterable
from dataclasses import FrozenInstanceError, field

Expand Down Expand Up @@ -717,6 +717,17 @@ class B:
def a(self, points: list):
...

def test_generic(self):
_Leaf_T = TypeVar("_Leaf_T")
class Tree(Generic[_Leaf_T]):
pass

@multidispatch
def f(t: Tree[int]):
pass

f(Tree())


class TestDataclass(TestCase):
def setUp(self):
Expand Down

0 comments on commit 2b9fa73

Please sign in to comment.