11"""
22undictify - Type-checked function calls at runtime
33"""
4+ import enum
45import inspect
56import sys
6- from enum import Enum
77from functools import wraps
88from typing import Any , Callable , Dict , List , Optional , Type , TypeVar , Union , get_type_hints , Tuple
99
2020TypeT = TypeVar ('TypeT' )
2121
2222
23- class ConverterTag (Enum ):
23+ class ConverterTag (enum . Enum ):
2424 """When to apply a converter"""
2525 OPTIONAL = 1
2626 MANDATORY = 2
@@ -278,6 +278,11 @@ def _get_value(func: WrappedOrFunc[TypeT],
278278 f'{ _get_type_name (type (result ))} ' )
279279 return result
280280 if Any not in allowed_types and not _isinstanceofone (value , allowed_types ):
281+ if _is_enum_type (func ):
282+ for entry in func : # type: ignore
283+ if value == entry .value :
284+ return entry
285+ raise TypeError (f'Unable to instantiate { func } from { value } .' )
281286 if optional_converters and param_name in optional_converters :
282287 result = optional_converters [param_name ](value )
283288 if not _isinstanceofone (result , allowed_types ):
@@ -300,11 +305,11 @@ def _get_value(func: WrappedOrFunc[TypeT],
300305 if isinstance (value , str ) and func is bool : # type: ignore
301306 return _string_to_bool (value )
302307 return func (value )
303- except ValueError :
308+ except ValueError as ex :
304309 raise TypeError (f'Can not convert { value } '
305310 f'from type { _get_type_name (value_type )} '
306311 f'into type { _get_type_name (func )} '
307- f'for key { param_name } .' )
312+ f'for key { param_name } .' ) from ex
308313
309314 raise TypeError (f'Key { param_name } has incorrect type: '
310315 f'{ _get_type_name (value_type )} instead of '
@@ -499,6 +504,14 @@ def _is_optional_type(the_type: Callable[..., TypeT]) -> bool:
499504 return any (_is_none_type (union_arg ) for union_arg in union_args )
500505
501506
507+ def _is_enum_type (the_type : Callable [..., TypeT ]) -> bool :
508+ """Return True if the type is an Enum."""
509+ try :
510+ return issubclass (the_type , enum .Enum ) # type: ignore
511+ except TypeError :
512+ return False
513+
514+
502515def _is_union_of_builtins_type (the_type : Callable [..., TypeT ]) -> bool :
503516 """Return True if the type is an Union only made of
504517 None, str, int, float and bool."""
0 commit comments