[issue35005] argparse should accept json and yaml argument types

paul j3 report at bugs.python.org
Wed Oct 17 13:38:36 EDT 2018


paul j3 <ajipanca at gmail.com> added the comment:

If I define a 'type' function like:

def readdata(astr):
    if astr.startswith('@'):
        with open(astr[1:], 'r') as f:
            d = json.load(f)
            return d
    else:
        return astr

I can use it to load a json file, or use the string directly:

In [59]: parser = argparse.ArgumentParser()
In [60]: parser.add_argument('-d','--data', type=readdata);
In [61]: parser.parse_args(['-d','@foo.json'])
Out[61]: Namespace(data={'foo': 12, 'bar': 'twelve'})
In [62]: parser.parse_args(['-d','xxx'])
Out[62]: Namespace(data='xxx')

This seems to behave as the 'curl' and 'ansible' examples you give, where the interpretation of the '@' is option specific.

A fully functional version of this type function needs to catch possible errors (not a file, not proper json, etc) and raise a ValueError or argparse.ArgumentTypeError.

The fact that 'curl -d' uses the '@', and 'fromfile_prefix_args' uses '@' in the documentation, should be seen as purely coincidental.  argparse would be just as happy using '#' or '%' as fromfile-prefix characters, just so long as the shell passes them unchanged to 'sys.argv'.  Conversely a type function can pay attention to special characters without needing to define them in the parser definition.

argparse doesn't define many custom 'type' functions.  Mostly it depends on people using stock Python functions like 'int' and 'float', or writing their own functions.  This keeps things simple for the common uses, while giving more advanced users a lot of flexibility.

This '@file' sensitivity could also be built into a custom Action subclass.  There too, argparse has defined a set of common cases, but lets the users customize to their heart's content.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue35005>
_______________________________________


More information about the Python-bugs-list mailing list