#!/usr/bin/env python # Nick R. Papior, 2016, August # This snippet shows that namespaces # are not retained across subparsers. # # Example call: # $0 --foo first --bar # $0 first --bar # Both of the above will fail due to the namespace.foo reference. # This will work: # $0 first --foo --bar from __future__ import print_function import argparse as arg # Create a parser and a subparser p = arg.ArgumentParser() # Add flag which is determining the top-level defaults p.add_argument('--foo', action='store_true', default=False) sp = p.add_subparsers() sp1 = sp.add_parser('first') # Add custom action class BarAction(arg.Action): def __call__(self, parser, namespace, value, option_string=None): """ Try and access the `foo` variable """ # Just to highlight the current namespace print(namespace.__dict__) # Perform action dependent on foo (this will error out as # the parent name-space is not passed... :() if namespace.foo: print('Do if TRUE') else: print('Do if FALSE') sp1.add_argument('--bar', nargs=0, action=BarAction) p.parse_args()