0

I already construct one custom action of argparse in python. However, when I add more custom actions, it seems not working.

class first_action(argparse.Action):
    def __call__(self, parser, args, values, option_string=None):
        print("the 1st")
        if ...:
            raise IndexError(...)
        elif ...:
            raise IndexError(...)
        else:
            setattr(args, self.dest, values)

This is the first custom action I made, and it worked

If I added more,

class second_action(argparse.Action):
    def __call__(self, parser, args, value, option_string=None):
        print("the 2nd")
        if ...:
            setattr(args, self.dest, fn1(value))
        else:
            setattr(args, self.dest, value)


class third_action(argparse.Action):
    def __call__(self, parser, args, value, option_string=None):
        print("the 3rd")
        if ...:
            setattr(args, self.dest, fn2(value))
        else:
            setattr(args, self.dest, value)

It worked but just passed the 2nd and 3rd actions and showed the message "the 1st" Here, only the 1st custom action is working.

parser.add_argument('-f', action=first_action)  <-- action working
parser.add_argument('-s', action=second_action) <-- action not working
parser.add_argument('-t', action=third_action)  <-- action not working
  • I forgot to add comment my guess: the problem might come from when it wasn't defined by user. I mean when arguments is made by following, args = get_parser().parse_args("-f".split()), instead of args = get_parser().parse_args("-f -s -t".split()) –  Feb 28 '19 at 04:42
  • 2
    RIght, an action is invoked (`called`) only if the corresponding flag is used in the command line. – hpaulj Feb 28 '19 at 04:53
  • @hpaulj Thanks! Then, is there any way to do something like the custom action which can work even for the case of the undefined flags? I want to apply custom action to the default value (None). –  Mar 04 '19 at 02:44
  • 1
    @hpaulj Custom default instead of custom action! –  Mar 04 '19 at 02:47
  • The `action` is only called when the argument is present in the user input. The `type` function will be evaluated on user input if given, or on string defaults if not. – hpaulj Mar 04 '19 at 03:07
  • @hpaulj Thanks a lot! But I reencountered trouble: how to call other args.OtherArgs in my custom type function. I need to refer another flag for one, which will be used the new type function, undefined flag. –  Mar 04 '19 at 10:18
  • @hpaulj I see your answer! https://stackoverflow.com/questions/20048048/argparse-default-option-based-on-another-option –  Mar 04 '19 at 11:11

0 Answers0