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

Fix: Throw error when attempting to dispatch on literal #67

Merged
merged 1 commit into from
Oct 15, 2024
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
4 changes: 4 additions & 0 deletions runtype/dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,10 @@ def define_function(self, f):
for signature in get_func_signatures(self.typesystem, f):
node = self.root
for t in signature:
if not isinstance(t, type):
# XXX this is a temporary fix for preventing certain types from being used for dispatch
if not getattr(t, 'ALLOW_DISPATCH', True):
raise ValueError(f"Type {t} cannot be used for dispatch")
node = node.follow_type[t]

if node.func is not None:
Expand Down
5 changes: 5 additions & 0 deletions runtype/pytypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,8 @@ def test_instance(self, obj, sampler=None):
class OneOf(PythonType):
values: typing.Sequence

ALLOW_DISPATCH = False

def __init__(self, values):
self.values = values

Expand All @@ -218,6 +220,7 @@ def cast_from(self, obj):
raise TypeMismatchError(obj, self)



class GenericType(base_types.GenericType, PythonType):
base: PythonDataType
item: PythonType
Expand Down Expand Up @@ -448,6 +451,8 @@ def cast_from(self, obj):


class _NoneType(OneOf):
ALLOW_DISPATCH = True # Make an exception

def __init__(self):
super().__init__([None])

Expand Down
18 changes: 18 additions & 0 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,24 @@ def f(t: Tree[int]):

f(Tree())

def test_literal_dispatch(self):
try:
@multidispatch
def f(x: typing.Literal[1]):
return 1

@multidispatch
def f(x: typing.Literal[2]):
return 2
except ValueError:
pass
else:
assert False

# If it was working..
# assert f(1) == 1
# assert f(2) == 2


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