This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author paul.j3
Recipients bethard, bob.ippolito, bradengroom, derelbenkoenig, paul.j3, rhettinger
Date 2018-10-18.19:35:31
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1539891331.57.0.788709270274.issue35005@psf.upfronthosting.co.za>
In-reply-to
Content
This kind of file read can be done just as easily after parsing.  For example using the function in my previous post:

In [127]: parser = argparse.ArgumentParser()
In [128]: parser.add_argument('-d','--data');
In [129]: args = parser.parse_args(['-d','@foo.json'])
In [130]: args
Out[130]: Namespace(data='@foo.json')
In [131]: args.data = readdata(args.data)
In [132]: args
Out[132]: Namespace(data={'foo': 12, 'bar': 'twelve'})

I've pointed out in various SO answers that using the 'type' parameter has just a few benefits.

- If you have many arguments that require this conversion, using type is a little more streamlined.  But it's not hard to iterate of a list of 'dest'.

- Using type routes the errors through the standard argparse mechanism, including the display of usage and system exit.  But the type function has to raise TypeError, ValueError, or ArgumentTypeError.  But you can also use 'parser.error(...)' in the post parsing processing.

Error handling is the make-or-break-it issue.  What kinds of errors do we want to handle?  What if the file name is bad or not accessible?  What if the file is poorly formatted JSON?  How do other APIs handle these errors?

For example the function that I defined can raise a FileNotFoundError if the file isn't found, or a JSONDecodeError if the file is badly formed.  JSONDecodeError is a subclass of ValueError, but IO errors are not.

If such a type function is added to argparse, the unittest file, test_argparse.py will have to have a number of test cases.  It will have to create a valid json test file, and possibly an invalid one.  It will have test working cases, and various error cases.  The amount of testing code is likely to be many times larger than the function code itself.  And we can't overlook the documentation additions.
History
Date User Action Args
2018-10-18 19:35:31paul.j3setrecipients: + paul.j3, rhettinger, bob.ippolito, bethard, bradengroom, derelbenkoenig
2018-10-18 19:35:31paul.j3setmessageid: <1539891331.57.0.788709270274.issue35005@psf.upfronthosting.co.za>
2018-10-18 19:35:31paul.j3linkissue35005 messages
2018-10-18 19:35:31paul.j3create