Skip to content

Case Insensitive Choice Type #569

Closed

Description

@sirosen

I've been converting a sprawling argparse CLI over to Click (and enjoying the improvements, btw), and I've run into a bit of an incompatibility between the two that I think should be easy for click to solve.
In short, this is a feature request for a case insensitive variant of click.Choice, or a general solution that handles that use case well.

I had case insensitive choice options like this before:

parser.add_argument('--foo', type=str.lower, choices=('apple', 'orange'))

Which means we could do commands like

$ mycmd --foo ORANGE
...
$ mycmd --foo apple

As far as I can tell, click.Choices doesn't support case insensitivity on the strings you use to choose.

This is easily implemented with a small custom type:

class CaseInsensitiveChoice(click.Choice):
    def convert(self, value, param, ctx):
        if value is None:
            return None
        return super(CaseInsensitiveChoice, self).convert(
            value.lower(), param, ctx)

However, I was a bit surprised that this was necessary -- I would expect Click to handle this with a keyword argument of some kind, off the shelf.

This could be a special case for doing string preprocessing, but it's maybe more justifiable as a feature on ParamType, something like argument_preprocessor=func, which would allow all ParamTypes to hook in some kind of user-supplied function.

I'm thinking of a final result something like click.Choice(('apple', 'orange'), argument_preprocessor=str.lower) for my own use case, but also supporting other potentially interesting things.

Activity

  1. untitaker commented on May 3, 2016

    @untitaker
    Contributor

    You can already implement this globally by passing extra options to your main command/group:

    @click.command(context_settings=dict(token_normalize_func=str.lower)))
    def cli():
        pass
    

    Perhaps token_normalize_func should additionally be a parameter on click.Choice, though I am not sure if you really want this configuration on a per-option basis.

  2. stuaxo commented on May 5, 2016

    @stuaxo

    Found myself wanting something a bit like this, just now - I tried this:

    def passfail(s):
        return {"pass": True, "fail": False}[s]
    
    @click.option("--force-result", default=None, type=click.Choice(['fail', 'pass']), context_settings=dict(token_normalize_func=passfail))
    

    But option doesn't take the context_settings_func

    Though in my case, maybe being able to pass a dict like {"pass": True, "fail": False} to Choice would work too.

  3. untitaker commented on May 5, 2016

    @untitaker
    Contributor

    Please re-read what I wrote above.

  4. stuaxo commented on May 5, 2016

    @stuaxo

    I had a look, but only want it on the one option, not all options of the command.

  5. stuaxo commented on May 5, 2016

    @stuaxo

    Will go with subclassing Choice :)

  6. untitaker commented on May 5, 2016

    @untitaker
    Contributor

    I assumed you misread and thought context_settings_func was a kwarg for click.option.

    Subclassing is definetly the best solution so far.

  7. stuaxo commented on May 5, 2016

    @stuaxo

    np, here's what I came up with (based on code @ the start of this ticket)

    class DictChoice(click.Choice):
        def __init__(self, choices):
            self.choices_dict = choices
            click.Choice.__init__(self, choices.keys())
    
        def convert(self, value, param, ctx):
            if value is None:
                return None
            initial_value = super(DictChoice, self).convert(value, param, ctx)
            return self.choices_dict.get(initial_value)
  8. stuaxo commented on May 5, 2016

    @stuaxo

    Oh, and example usage:

    @click.option("--force-result", default=None, type=DictChoice({'fail': False, 'pass': True}))
  9. sirosen commented on Jun 13, 2016

    @sirosen
    ContributorAuthor

    Sorry for not checking back on this sooner. I forgot about it. 😅

    @untitaker I think there are legitimate use-cases for being case insensitive some places, but not others. That rules out changing the tokenizer as an option.
    My particular need pertains to a CLI which wraps a REST API I'm working with.
    As much as possible I want to be case-insensitive, but rarely I need to consume strings destined for the backend API.

    Being able to patch over the tokenizer used for a given option would be perfect, and be a bit more flexible than case-insensitivity specifically for Choice types.
    It also sounds harder to implement though.

    I think a good number of people probably have type=str.lower in their Argparse structure, but require case-sensitivity elsewhere.
    I don't like that transitioning those options required implementing my own ParamType.

    I guess this depends a bit on how important feature parity with Argparse is. I don't think that custom types count for that -- that's an extension point of Click, not "out of the box" functionality.

  10. added a commit that references this issue on Nov 8, 2017
    f90c541
  11. added a commit that references this issue on May 15, 2018
    138a6e3
  12. added this to the 7.0 milestone on Sep 10, 2018
  13. added 2 commits that reference this issue on Oct 8, 2018
  14. added a commit that references this issue on Oct 29, 2018
  15. locked as resolved and limited conversation to collaborators on Nov 13, 2020
  16. added
    parsing
    on Aug 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    parsing

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions