click icon indicating copy to clipboard operation
click copied to clipboard

Unexposed option name is `None` when the parameter name is not a python identifier

Open azmeuk opened this issue 1 year ago • 1 comments

I would like to have dots in option names. As click requires option names to be valid python identifiers, I would like to use unexposed options to make dots in option names possible, and a custom callback to store the option name somewhere:

import click


def option_callback(ctx, param, value):
    ctx.ensure_object(dict)
    ctx.obj.setdefault("params", {})[param.name] = value

    return value


@click.command()
@click.option("--foo.foo", expose_value=False, callback=option_callback)
@click.option("--bar-bar", expose_value=False, callback=option_callback)
@click.pass_obj
def cli(obj):
    click.echo(obj["params"])


if __name__ == "__main__":  # pragma: no cover
    cli()

In that situation, in the callback context, option.name is None if the original option name is not a valid identifier:

$ python example.py --foo.foo baz --bar-bar baz
{None: 'baz', 'bar_bar': 'baz'}

I suppose this is due to those lines: https://github.com/pallets/click/blob/99015e1456b6952054fda8312b40ea646737168d/src/click/core.py#L2594-L2595

Ideally I would love a simple way to use non identifier option names, like proposed in https://github.com/pallets/click/discussions/2433. In the meantime I would suggest to allow Option.name to have its original value instead of None for unexposed option. I would volunteer for a PR if this is accepted.

What do you think?

  • Python version: 3.12
  • Click version: 8.1.7

azmeuk avatar Aug 26 '24 15:08 azmeuk

In general, I am open to new community sourced ideas, and I appreciate the effort you put into this. However, Click is so widely used, that I would like to have more comprehensive docs and better test coverage before anything major is added, unless there is very clear community support. I will continue to keep an eye on this to see if it gathers community support.

Rowlando13 avatar Apr 06 '25 00:04 Rowlando13