@@ -44,23 +44,65 @@ def __str__(self):
4444def _make_assert_is_of_type ():
4545 try :
4646 from typeguard import check_type
47+ try :
48+ from typing import Union
49+ except ImportError :
50+ # (a) typing is not available, transform iterables of types into several calls
51+ def assert_is_of_type (field , value , typ ):
52+ """
53+ Type checker relying on `typeguard` (python 3.5+)
54+
55+ :param field:
56+ :param value:
57+ :param typ:
58+ :return:
59+ """
60+ try :
61+ # iterate on the types
62+ t_gen = (t for t in typ )
63+ except TypeError :
64+ # not iterable : a single type
65+ try :
66+ check_type (field .qualname , value , typ )
67+ except Exception as e :
68+ # raise from
69+ new_e = FieldTypeError (field , value , typ )
70+ new_e .__cause__ = e
71+ raise new_e
72+ else :
73+ # iterate and try them all
74+ e = None
75+ for t in t_gen :
76+ try :
77+ check_type (field .qualname , value , typ )
78+ return # success !!!!
79+ except Exception as e :
80+ pass # failed: lets try another one
81+
82+ # raise from
83+ if e is not None :
84+ new_e = FieldTypeError (field , value , typ )
85+ new_e .__cause__ = e
86+ raise new_e
4787
48- def assert_is_of_type (field , value , typ ):
49- """
50- Type checker relying on `typeguard` (python 3.5+)
51-
52- :param field:
53- :param value:
54- :param typ:
55- :return:
56- """
57- try :
58- check_type (field .qualname , value , typ )
59- except Exception as e :
60- # raise from
61- new_e = FieldTypeError (field , value , typ )
62- new_e .__cause__ = e
63- raise new_e
88+ else :
89+ # (b) typing is available, use a Union
90+ def assert_is_of_type (field , value , typ ):
91+ """
92+ Type checker relying on `typeguard` (python 3.5+)
93+
94+ :param field:
95+ :param value:
96+ :param typ:
97+ :return:
98+ """
99+ try :
100+ check_type (field .qualname , value , Union [typ ])
101+ except Exception as e :
102+ # raise from
103+ new_e = FieldTypeError (field , value , typ )
104+ new_e .__cause__ = e
105+ raise new_e
64106
65107 except ImportError :
66108 try :
0 commit comments