Search code examples
pythonargparse

argparse: Dynamically use the value chosen for earlier argument for later argument


Is it possible to use an argument for a later argument?

from argparse import ArgumentParser

def get_args():
    parser = ArgumentParser(description="Data Generator")
    parser.add_argument('--name', required=True, type=str, help='Pick one: x, y, z')
    parser.add_argument('--save_path', type=str, default='C:/Users/User1/Desktop/', help='The save path')
    args = parser.parse_args()
    return args

For instance, I would like to use the value the user includes in --name to be later and automatically tacked on the --save_path value. How might I do this?


Solution

  • args is nothing but a simple container object that holds its values as attributes. You can just modify it before returning it.

    Given that name and save_path seem to be directory or file names, you could use os.path.join to add name to save_path.

    import os.path
    
    # ...
    
    def get_args():
        # ...
        args = parser.parse_args()
        args.save_path = os.path.join(args.save_path, args.name)
        return args