#! /usr/bin/env python3.6
# -*- coding: utf-8 -*-
from overloading import overload, overloaded, overloads
from unittest import TestCase, main
from typing import Union, Dict, Any, Iterable
class TestOverloading(TestCase):
# Use overloading on functions with different types
_add_types = Union[int, str, dict, set]
@overload
@staticmethod
def add(x: int, y: int) -> int:
return x + y
@overload
@staticmethod
def add(x: str, y: str) -> str:
return x + y
@overload
@staticmethod
def add(x: Dict[Any, Any], y: Dict[Any, Any]) -> Dict[Any, Any]:
return {**x, **y}
@overload
@staticmethod
def add(x: set, y: set) -> set:
return x | y
@staticmethod
def complete_add(x: _add_types, y: _add_types) -> _add_types:
class TypeMismatchError(TypeError):
pass
if type(x) != type(y):
raise TypeMismatchError(
f'complete_add expected arguments of similar type, received {type(x)}, {type(y)}'
)
if (type(x) is int and type(y) is int):
return x + y
elif type(x) is str and type(y) is str:
return x + y
elif type(x) is dict and type(y) is dict:
return {**x, **y}
elif type(x) is set and type(y) is set:
return x | y
else:
ts = ', '.join(_add_types.__args__)
raise TypeError(
f'complete_add expected arguments of type {ts} received {type(x)}'
)
def test1(self) -> None:
self.assertEqual(self.add(1, 2), self.complete_add(1, 2))
self.assertEqual(self.add('Brandon', ' Doyle'), self.complete_add('Brandon', ' Doyle'))
self.assertEqual(self.add({1: 'one'}, {2: 'two'}), self.complete_add({1: 'one'}, {2: 'two'}))
self.assertEqual(self.add({1}, {2}), self.complete_add({1}, {2}))
if __name__ == '__main__':
main()
Traceback (most recent call last):
File "./test_overloading.py", line 9, in <module>
class TestOverloading(TestCase):
File "./test_overloading.py", line 21, in TestOverloading
def add(x: str, y: str) -> str:
File "/usr/local/lib/python3.6/site-packages/overloading-0.5.0-py3.6.egg/overloading.py", line 63, in overload
return register(__registry[fname], func)
File "/usr/local/lib/python3.6/site-packages/overloading-0.5.0-py3.6.egg/overloading.py", line 207, in register
dup_sig = sig_cmp(signature, fninfo.signature)
File "/usr/local/lib/python3.6/site-packages/overloading-0.5.0-py3.6.egg/overloading.py", line 669, in sig_cmp
match = type_cmp(t1, t2)
File "/usr/local/lib/python3.6/site-packages/overloading-0.5.0-py3.6.egg/overloading.py", line 702, in type_cmp
if isinstance(t1, typing.UnionMeta) and isinstance(t2, typing.UnionMeta):
AttributeError: module 'typing' has no attribute 'UnionMeta'