Search code examples
pythonpython-click

How to make an argument optional based upon another argument's value in Python using click?


I have this following CLI method that I have created using click module in python.

import click

@click.command()
@click.argument("name")
@click.option("--provider", "-p", default="aws", help="Cloud Provider")
@click.argument("view", required=True)

def create(name, view, provider):
   print name
   print view
   print provider

if __name__ == '__main__':
    create()

I want to manipulate view option based on the value it gets for --provider. For example if --provider is aws then required=True for view else required=False making view optional while running my code.


Solution

  • There's no need for anything fancy, something like this will work

    def create(name, provider, view=None):
        if provider == "aws" and view is None:
            raise AttributeError("View is required when provider is 'aws'")