[New-bugs-announce] [issue30220] Why are the custom messages for ValueError and TypeError suppressed in argparse?
Pedro
report at bugs.python.org
Mon May 1 12:19:51 EDT 2017
New submission from Pedro:
ArgumentParser._get_value() has two exception handlers: one for ArgumentTypeError, and one for (TypeError, ValueError). But in the latter case, any custom message I include the TypeError or ValueError is ignored and replaced with a generic "invalid value" message.
I don't see why the module wouldn't first check for a custom message in a TypeError or ValueError exception, as it does for ArgumentTypeError, and only use the generic message if a custom one is not specified. The current behavior does not let you to give the user a detailed reason for the exception unless you raise ArgumentTypeError, which is considered an implementation detail as mentioned in #20039, and also doesn't feel right for errors that are not related to the argument's type.
Code to reproduce:
import argparse
def nonnegative_not_suppressed(arg):
try:
x = int(arg)
if x >= 0:
return x
else:
raise argparse.ArgumentTypeError('Enter a nonnegative integer')
except:
raise argparse.ArgumentTypeError('Enter a nonnegative integer')
def nonnegative_suppressed(arg):
try:
x = int(arg)
if x >= 0:
return x
else:
raise ValueError('Enter a nonnegative integer')
except:
raise ValueError('Enter a nonnegative integer')
p = argparse.ArgumentParser('parser')
p.add_argument('--no-suppress', type=nonnegative_not_suppressed)
p.add_argument('--suppress', type=nonnegative_suppressed)
p.parse_args(['--no-suppress', '-4']) # Displays "Enter a nonnegative integer"
p.parse_args(['--suppress', '-4']) # Displays "invalid nonnegative_suppressed value: '-4'"
----------
components: Extension Modules
messages: 292669
nosy: pgacv2
priority: normal
severity: normal
status: open
title: Why are the custom messages for ValueError and TypeError suppressed in argparse?
type: enhancement
versions: Python 3.5
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue30220>
_______________________________________
More information about the New-bugs-announce
mailing list