more flexible logic that try converting str to number with all classinfo and fall back on error message when not successfull

This commit is contained in:
giacomo 2022-04-28 13:50:32 +01:00 committed by Pavel Minaev
parent 50632736bf
commit 7597e466c4

View file

@ -7,9 +7,8 @@
import builtins
import json
import operator
import string
import numbers
import operator
JsonDecoder = json.JSONDecoder
@ -108,16 +107,14 @@ def of_type(*classinfo, **kwargs):
def validate(value):
if (optional and value == ()) or isinstance(value, classinfo):
return value
elif (
isinstance(value, str)
and all(x in string.digits + "." for x in value)
and any(issubclass(x, numbers.Number) for x in classinfo)
):
try:
return int(value)
except ValueError:
return float(value)
else:
for one_info in classinfo:
if issubclass(one_info, numbers.Number):
try:
return one_info(value)
except ValueError:
pass
if not optional and value == ():
raise ValueError("must be specified")
raise TypeError("must be " + " or ".join(t.__name__ for t in classinfo))