views:

31

answers:

1

Using the argparse module, is it possible to perform multiple actions for a given argument?

Specifically, I'd like to provide a -l/--list option with nargs='?' that will change the behaviour of the program from its main function to one of giving information about all possibilities in a set or about one particular possibility.

Normally there will be a namespace attribute that contains a function to be called after parsing; I would like the -l option to both change this attribute and optionally store its argument in a different attribute.

Is this possible?

+1  A: 

Simply implement your own Action subclass. This basically looks like this:

class ListAction(argparse.Action):
    def __call__(parser, namespace, values, option_string=None):
        setattr(namespace, 'list', values[0])
        do_something_completely_different()

The argparse documentation has more details.

lunaryorn
ah hahh... I missed that section of the docs. Thanks!
intuited