Simplify argparser.type_check
If the value isn't param.default, it will always be a string or a flag, as type_conv never gets called when the function is called from Python.
This commit is contained in:
parent
284d4e4b97
commit
e4d84b0bfc
@ -114,22 +114,17 @@ def type_conv(param, typ, value, *, str_choices=None):
|
||||
if value is param.default:
|
||||
return value
|
||||
|
||||
assert isinstance(value, str), repr(value)
|
||||
|
||||
if utils.is_enum(typ):
|
||||
if isinstance(value, typ):
|
||||
return value
|
||||
assert isinstance(value, str)
|
||||
_check_choices(param, value, [arg_name(e.name) for e in typ])
|
||||
return typ[value.replace('-', '_')]
|
||||
elif typ is str:
|
||||
assert isinstance(value, str)
|
||||
if str_choices is not None:
|
||||
_check_choices(param, value, str_choices)
|
||||
return value
|
||||
elif callable(typ):
|
||||
# int, float, etc.
|
||||
if isinstance(value, typ):
|
||||
return value
|
||||
assert isinstance(value, str)
|
||||
try:
|
||||
return typ(value)
|
||||
except (TypeError, ValueError):
|
||||
|
@ -415,6 +415,8 @@ class Command:
|
||||
value = argparser.type_conv(param, typ, value, str_choices=choices)
|
||||
elif typ is None:
|
||||
pass
|
||||
elif typ is bool: # no type conversion for flags
|
||||
assert isinstance(value, bool)
|
||||
else:
|
||||
value = argparser.type_conv(param, typ, value)
|
||||
|
||||
|
@ -80,11 +80,9 @@ class TestArgumentParser:
|
||||
|
||||
|
||||
@pytest.mark.parametrize('types, value, expected', [
|
||||
([Enum], Enum.foo, Enum.foo),
|
||||
([Enum], 'foo', Enum.foo),
|
||||
([Enum], 'foo-bar', Enum.foo_bar),
|
||||
|
||||
([int], 2, 2),
|
||||
([int], '2', 2),
|
||||
([int, str], 'foo', 'foo'),
|
||||
])
|
||||
@ -132,12 +130,13 @@ def test_multitype_conv_invalid_type():
|
||||
assert str(excinfo.value) == "foo: Unknown type None!"
|
||||
|
||||
|
||||
def test_conv_default_param():
|
||||
@pytest.mark.parametrize('value, typ', [(None, None), (42, int)])
|
||||
def test_conv_default_param(value, typ):
|
||||
"""The default value should always be a valid choice."""
|
||||
def func(foo=None):
|
||||
def func(foo=value):
|
||||
pass
|
||||
param = inspect.signature(func).parameters['foo']
|
||||
assert argparser.type_conv(param, str, None, str_choices=['val']) is None
|
||||
assert argparser.type_conv(param, typ, value, str_choices=['val']) == value
|
||||
|
||||
|
||||
def test_conv_str_type():
|
||||
|
Loading…
Reference in New Issue
Block a user