Skip to content

Commit 9839148

Browse files
authored
Merge pull request #15 from pganssle/support_single_dispatch
Add support for singledispatch (does not work with methods)
2 parents 4a0bf35 + 5e53fa7 commit 9839148

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

requirements_dev.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ wheel
33
tox
44
coverage
55
Sphinx
6+
singledispatch; python_version <= '3.3'
67
pytest >= 3.0; python_version != '3.3'
78
pytest < 3.3; python_version == '3.3'
89
pytest-runner

src/variants/_variants.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ def __init__(self, primary_func):
3838
def __call__(self, *args, **kwargs):
3939
return self.__main_form__(*args, **kwargs)
4040

41+
def __getattr__(self, key):
42+
return getattr(self.__main_form__, key)
43+
4144
def _add_variant(self, var_name, vfunc):
4245
self._variants.add(var_name)
4346
setattr(self, var_name, vfunc)

tests/test_single_dispatch.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
from __future__ import division
2+
3+
import pytest
4+
5+
try:
6+
from functools import singledispatch
7+
except ImportError:
8+
from singledispatch import singledispatch
9+
10+
import variants
11+
12+
13+
###
14+
# Example implementation - single dispatched function
15+
@variants.primary
16+
@singledispatch
17+
def add_one(arg):
18+
return arg + 1
19+
20+
21+
@add_one.variant('from_list')
22+
@add_one.register(list)
23+
def add_one(arg):
24+
return arg + [1]
25+
26+
27+
@add_one.variant('from_tuple')
28+
@add_one.register(tuple)
29+
def add_one(arg):
30+
return arg + (1,)
31+
32+
33+
### Tests
34+
def test_single_dispatch_int():
35+
assert add_one(1) == 2
36+
37+
38+
def test_single_dispatch_list():
39+
assert add_one([2]) == [2, 1]
40+
41+
42+
def test_single_dispatch_tuple():
43+
assert add_one((2,)) == (2, 1)
44+
45+
46+
def test_dispatch_list_variant_succeeds():
47+
assert add_one.from_list([4]) == [4, 1]
48+
49+
50+
@pytest.mark.parametrize('arg', [3, (2,)])
51+
def test_dispatch_list_variant_fails(arg):
52+
with pytest.raises(TypeError):
53+
add_one.from_list(arg)
54+
55+
56+
def test_dispatch_tuple_variant_succeeds():
57+
assert add_one.from_tuple((2,)) == (2, 1)
58+
59+
60+
@pytest.mark.parametrize('arg', [3, [2]])
61+
def test_dispatch_tuple_variant_fails(arg):
62+
with pytest.raises(TypeError):
63+
add_one.from_tuple(arg)

0 commit comments

Comments
 (0)