Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom type or action on default argument with argparse

I want to convert arguments I pass to argparse in an other format; the idea is to pass a number (a float typically) and to convert it in a string (Fortran notation for a float, typically).

First, I tried to create a custom type

def FortranFloat(value):
    vfloat = float(value)
    vfloat = str(vfloat) + "d0"
    return vfloat

parser = argparse.ArgumentParser()
parser.add_argument("--xmin=", dest="xmin", type=FortranFloat, default=-2.0)
args = parser.parse_args()

It works well... if I actually give the --xmin= argument. Else, it just keeps the -2.0, without converting it in -2.0d0 as I wish. I therefore thought that it could be easier to give the default value the format I want, so replacing 2.0 by '2.0d0'... The interesting thing is that it is evaluated, because it crashes and raise the following error

argparse.ArgumentError: argument --xmin=: invalid FortranFloat value: '-2.0d0'

To get around this problem I tried to create a custom action

class FortranConverter(argparse.Action):
    def __call__(self, parser, namespace, values, option_strings=None):
        if type(values) is float:
            values = str(values) + "d0"
            setattr(args, self.dest, values)

parser = argparse.ArgumentParser()
parser.add_argument("--xmin=", dest="xmin", type=float, default=-2.0, action=FortranConverter)
args = parser.parse_args()

That didn't work either. It doesn't even seem to go through my action (if I print something in the __call__, it will just ignore it).

Any thought, idea or explanation would be appreciated!

like image 320
MBR Avatar asked May 23 '14 15:05

MBR


1 Answers

If the default is a string, it is passed through the type function. Anything else is used as is: setattr(namespace, dest, default). Have you tried '-2.0'? Your FortranFloat should convert that to '-2.0d0'.

Another option is to modify your FortranFloat so it recognizes a string with 'd0', and passes it through unchanged.

The argument string is passed through type before it is passed to the action. And if I recall the code correctly, a default never goes through the action; it is set directly.

You don't need it, but to work, your FortranConverter function should use setattr(namespace, self.dest, values).

What were you trying to accomplish with nargs=0? Actions like 'store_true' use that to indicated that they don't take any arguments. Otherwise it isn't a useful value for the programmer.

like image 139
hpaulj Avatar answered Sep 30 '22 13:09

hpaulj