Skip to content

Click 8.2.0 ignores is_flag options that have a type #2894

@andy-maier

Description

@andy-maier

Click 8.2.0 ignores the use of options defined with is_flag and type=str.

Of course, combining is_flag and type=str does not make sense, but it happened in one of our projects. Click before 8.2.0 ignored type=str and processed this as expected for is_flag.

Click 8.2.0 does not set a value for such an option.

I could trace this change to PR #2829 - If I install click 8.2.0 and manually undo the change in core.py that is done by that PR, it works as before.

To reproduce:

  1. Have a file main.py with:
import click

@click.group(invoke_without_command=True)
@click.option('-x', '--transpose', type=str, is_flag=True,
              help='Transpose the output table.')
def cli(transpose):
    print(f"Debug: transpose={transpose}")
    return 0
  1. Reproduce with click 8.2.0:
$ pip install click==8.2.0
$ python -c "import main,sys; sys.argv=['cli', '--transpose']; main.cli()"
Debug: transpose=None
  1. Verify that click 8.2.0 with PR Only try to set flag_value if is_flag is true #2829 undone works:
# perform the undo in core.py (see below)
$ python -c "import main,sys; sys.argv=['cli', '--transpose']; main.cli()"
Debug: transpose=True
  1. Verify that click 8.1.8 works:
$ pip install click==8.1.8
$ python -c "import main,sys; sys.argv=['cli', '--transpose']; main.cli()"
Debug: transpose=True

The "undo" of PR #2829 has the following changes in core.py, starting at line 2613:

        # Undo PR 2829: Added the following two lines
        if flag_value is None:
            flag_value = not self.default
        self.type: types.ParamType
        if is_flag and type is None:
            # Undo PR 2829: Removed the following two lines
            # if flag_value is None:
            #     flag_value = not self.default
            # Re-guess the type from the flag value instead of the
            # default.
            self.type = types.convert_type(None, flag_value)

Environment:

  • Python version: 3.12.7 on macOS (it happens on all Python versions supported by click 8.2.0, but not on all OSs)
  • Click version: 8.2.0

Based on our CI test run, the issue happens only on macOS and Windows, but not on Ubuntu:
https://github.com/zhmcclient/zhmccli/actions/runs/14949544297. I did not investigate why it does not happen on Ubuntu.

The fix for projects using click is of course to remove type when is_flag is used.

Even though this is basically an incorrect use of click, I would expect click to surface this as an incorrect use, instead of silently not setting a value for the option.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions