ANIL
ANIL

Reputation: 2682

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.

Upvotes: 0

Views: 313

Answers (1)

C_Z_
C_Z_

Reputation: 7816

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'")

Upvotes: 1

Related Questions