Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
Version 8.2.1
-------------

- Fixes flag default handling for boolean options. :issue:`2897` :pr:`2912`

Version 8.2.0
-------------
Expand Down
6 changes: 6 additions & 0 deletions src/click/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -2618,6 +2618,12 @@ def __init__(
# default.
self.type = types.convert_type(None, flag_value)

if is_flag and isinstance(self.type, types.BoolParamType):
# If the type is a boolean, we need to set the flag_value
# to True or False depending on the default.
if flag_value is None:
flag_value = not self.default

Comment thread
john0isaac marked this conversation as resolved.
self.is_flag: bool = is_flag
self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType)
self.flag_value: t.Any = flag_value
Expand Down
40 changes: 40 additions & 0 deletions tests/test_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,43 @@ def foo(name):

result = runner.invoke(cli, ["foo", "--help"], default_map={"foo": {"name": True}})
assert "default: name" in result.output


def test_flag_default_bool(runner):
"""test flag with default bool"""

@click.command()
@click.option("--foo", is_flag=True, default=False, type=click.BOOL)
@click.option("--bar", is_flag=True, default=False, type=bool)
@click.option("--baz", is_flag=True, default=True, type=click.BOOL)
@click.option("--qux", is_flag=True, default=True, type=bool)
def cli(foo, bar, baz, qux):
assert isinstance(foo, bool)
assert isinstance(bar, bool)
assert isinstance(baz, bool)
assert isinstance(qux, bool)
click.echo(f"foo: {foo}, bar: {bar}, baz: {baz}, qux: {qux}")

result = runner.invoke(cli, [])
Comment thread
john0isaac marked this conversation as resolved.
assert not result.exception
assert "foo: False, bar: False, baz: True, qux: True" in result.output

result = runner.invoke(cli, ["--foo"])
assert not result.exception
assert "foo: True, bar: False, baz: True, qux: True" in result.output

result = runner.invoke(cli, ["--bar"])
assert not result.exception
assert "foo: False, bar: True, baz: True, qux: True" in result.output

result = runner.invoke(cli, ["--baz"])
assert not result.exception
assert "foo: False, bar: False, baz: False, qux: True" in result.output

result = runner.invoke(cli, ["--qux"])
assert not result.exception
assert "foo: False, bar: False, baz: True, qux: False" in result.output

result = runner.invoke(cli, ["--foo", "--bar", "--baz", "--qux"])
assert not result.exception
assert "foo: True, bar: True, baz: False, qux: False" in result.output