Multiple options mixing #2297
Answered
by
jwodder
pyhedgehog
asked this question in
Q&A
-
I need something like feature switches, but with argument. #!/usr/bin/env python3
import click
import dataclasses
@dataclasses.dataclass
class KindRef:
kind: str
ref: str
class KindRefType(click.ParamType):
name = 'ref'
def __init__(self, kind):
self.kind = kind
super().__init__()
def convert(self, value, param, ctx):
return KindRef(self.kind, value)
@click.command()
@click.option('--image', '--iid', 'ref', type=KindRefType('image'), help="Name or id of image", required=True)
@click.option('--container', '--cid', 'ref', type=KindRefType('container'), help="Name or id of container", required=True)
@click.option('--service', '--task', 'ref', type=KindRefType('service'), help="Name of service or task", required=True)
def main(ref):
print(ref)
if __name__=='__main__':
main() Then I'm running: $ ./qq.py --help
Usage: qq.py [OPTIONS]
Options:
--image, --iid REF Name or id of image [required]
--container, --cid REF Name or id of container [required]
--service, --task REF Name of service or task [required]
--help Show this message and exit.
$ ./qq.py
Usage: qq.py [OPTIONS]
Try 'qq.py --help' for help.
Error: Missing option '--image' / '--iid'. It's fine. But later I've got following: $ ./qq.py --image 123
KindRef(kind='service', ref='123')
$ ./qq.py --container 123
KindRef(kind='service', ref='123')
$ ./qq.py --service 123
KindRef(kind='container', ref='123') What I'm doing wrong? $ python3 -m pip freeze|grep click
click==8.0.1 PPS: Upgrading to 8.1.3 doesn't changes this behaviour. |
Beta Was this translation helpful? Give feedback.
Answered by
jwodder
May 27, 2022
Replies: 1 comment
-
This issue may be relevant: #1730. The code I eventually ended up going with in that case looks like: from collections import namedtuple
import click
Apple = namedtuple('Apple', 'value')
Banana = namedtuple('Banana', 'value')
Coconut = namedtuple('Coconut', 'value')
def set_option(ctx, param, value):
if value is not None:
ctx.params["option"] = value
return value
@click.command()
@click.option('-a', '--apple', type=Apple, callback=set_option, expose_value=False)
@click.option('-b', '--banana', type=Banana, callback=set_option, expose_value=False)
@click.option('-c', '--coconut', type=Coconut, callback=set_option, expose_value=False)
def main(option=None):
click.echo(option)
if __name__ == '__main__':
main() |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
pyhedgehog
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This issue may be relevant: #1730. The code I eventually ended up going with in that case looks like: