Python argparse custom actions with additional arguments passed

user880248 picture user880248 · Dec 26, 2011 · Viewed 17.2k times · Source
import argparse

class customAction(argparse.Action):
    def __call__(self, parser, args, values, option_string=None):
       setattr(args, self.dest, values)

parser = argparse.ArgumentParser()
parser.add_argument('-e', '--example', action=customAction)

I want to pass additional arguments to customAction when the option -e is triggered, e.g. a instance of another class. How can I do this? Everything I have tried has errored out.

Answer

jfs picture jfs · Dec 26, 2011
def make_action(additional_arg):
    class customAction(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            print(additional_arg)
            setattr(args, self.dest, values)
    return customAction
#...
parser.add_argument('-e', '--example', action=make_action('your arg'))