Skip to content

fix: guard default value comparison against types with strict __eq__#3327

Closed
Bahtya wants to merge 1 commit intopallets:mainfrom
Bahtya:fix/default-comparison-3298
Closed

fix: guard default value comparison against types with strict __eq__#3327
Bahtya wants to merge 1 commit intopallets:mainfrom
Bahtya:fix/default-comparison-3298

Conversation

@Bahtya
Copy link
Copy Markdown

@Bahtya Bahtya commented Apr 8, 2026

Problem

Fixes #3298

When a non-string default value (e.g. semver.Version) is used with an @click.option, Click tries to generate help text and compares the default value against an empty string using ==. Types like semver.Version implement __eq__ to only accept strings that parse as valid semver, so Version(1,0,0) == "" raises ValueError.

Root Cause

In core.py line ~3113:

elif default_value == "":
    default_string = "\"\""

This equality check is triggered for any type of default value, not just strings. For types with strict __eq__ implementations, this crashes.

Fix

Add an isinstance(default_value, str) guard before the == "" check, so non-string types fall through to the str(default_value) branch which works correctly for all types.

Testing

import click
from semver import Version

class SemverType(click.ParamType):
    name = "semver"
    def convert(self, value, param, ctx):
        if isinstance(value, Version):
            return value
        return Version.parse(value)

@click.command()
@click.option("--version", type=SemverType(), default=Version(1, 0, 0))
def cli(version):
    click.echo(f"Version: {version}")

# This now works without ValueError
from click.testing import CliRunner
runner = CliRunner()
result = runner.invoke(cli, ["--help"])

Existing test suite passes (331 passed; 1 pre-existing failure unrelated to this change).

Fixes pallets#3298. When a non-string default value (e.g. semver.Version) is
used with an option, Click help text builder compares it against an
empty string using ==. Types that implement __eq__ to only accept
specific types will raise a ValueError.

Add an isinstance(default_value, str) guard before the equality check
so non-string types fall through to str(default_value) instead.
@davidism davidism closed this Apr 8, 2026
@kdeldycke kdeldycke added this to the 8.3.3 milestone Apr 9, 2026
@kdeldycke
Copy link
Copy Markdown
Collaborator

AI slop duplicating: #3299

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

semver.Version as default causing an error

3 participants