paul j3 <ajipa...@gmail.com> added the comment:

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.

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue35005>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to