Skip to content

Parser rewrite 2 - #3924

Open
Rowlando13 wants to merge 17 commits into
pallets:mainfrom
Rowlando13:parser-rewrite-2
Open

Rowlando13 wants to merge 17 commits into
pallets:mainfrom
Rowlando13:parser-rewrite-2

Conversation

@Rowlando13

@Rowlando13 Rowlando13 commented Nov 19, 2026 •

Copy link
Copy Markdown
Member
  • Remove old parser that was private
  • Replace with with a private function Command._parse_args
  • That function is factored into static methods for _build_opt_tables, _scan_tokens, and _assign_args.
  • Remove protected args
  • Increase end to end test coverage for all cases I could think of related to parser branches
  • So far as I can tell no behavior changes for new parser except a bugfix. The parser now errors when a user invokes a normalized option that has collapsed to another option such that one is unreachable. It does not error when one of the names for an option collapses to another such as -S to -s for lowercase token normalization, when they are just other names for the same thing.
    -split_arg_string is now public. It was basically halfway public already where we import it in the docs but not from the top level to show how to make you own shell completion. Its very small.

ToDo:

  • Make fixes from reviews

@Rowlando13
Rowlando13 marked this pull request as draft November 19, 2026 07:38
@kdeldycke kdeldycke added the parsing Parsing, parameters, commands, chaining, context label Nov 19, 2026
@kdeldycke kdeldycke added this to the 9.0.0 milestone Nov 19, 2026
@kdeldycke

Copy link
Copy Markdown
Collaborator

Oh. Before I even start to look at this PR, what is the goal of this one? Just a rebase on top of main of @davidism 's previous attempt of the parser-rewrite-1 branch? Is it in a reviewable state of is this just quick experiment to see what sticks and what need more work? 😁

@Rowlando13

Copy link
Copy Markdown
Member Author

@kdeldycke its ready for review.

Comment thread src/click/_parser.py
@@ -0,0 +1 @@
from __future__ import annotations

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove this file.

@kdeldycke kdeldycke left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, so this PR is indeed a reboot of David's parser-rewrite-1 and keeps its refactor big points.

I like how this PR splits David's initial inline code into smaller pieces like _build_opt_tables, _scan_tokens and _assign_args, with the additional _OptTables. Even if private, it already helps me clean some fancy stuff I do in Click Extra around introspection. And gives more flexibility to other users, at their own risks off course.

I like the TypeError when two option names collides. There are probably some overlaps with #3827 but I will revise my PR against this one once it is merged.

I left a lot of test in my review to illustrate edge-cases that need to be documented, covered, discussed or fixed. Not sure if these were intentionals.

But all in all I like this PR ! Only a small effort and I guess we can start laying the fondation for 9.0.0. If we decide to merge, should we create a new 9.x branch? Or push to main, declare it 9.x and merge the upcoming 8.6.0 to stable?

Comment thread src/click/core.py

claimed[name] = (param, original, is_secondary)
prefix, value = _split_opt(name)
opt_prefixes.add(prefix[0])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You take prefix[0] here without checking it. So an option declared without dashes, like @click.option("fruit-name"), now gives a different error: we get the less-informative IndexError: string index out of range instead of the original ValueError: Invalid start character for option (fruit-name).

Comment thread src/click/core.py
def parse_args(self, ctx: Context, args: list[str]) -> list[str]:
return self._parse_args(ctx, args)

def _parse_args(self, ctx: Context, args: list[str]) -> list[str]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method still parses and processes arguments in one go. I propose to use the oportunity to split the pure parsing part from the processing part, as suggested in #2205 (comment)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And this address #1279 BTW.

Comment thread CHANGES.md
@@ -1,7 +1,24 @@
## Version 8.6.0
## Version 9.0.0

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keep the 8.6.0 changelog as we need a 8.6.0 to deprecate stuff explicitly before 9.0.0

Comment thread src/click/core.py
self._exit_stack = ExitStack()

@property
def protected_args(self) -> list[str]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe you should delete this property altogether since it is already marked for deletion for 9.0.0 and you already removed self._protected_args?

Comment thread src/click/core.py
context. ``Command.show_default`` overrides this default for the
specific command.
.. versionchanged:: 8.2

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe add a note here to inform about protected_args deletion.

Comment thread CHANGES.md
`-v` and `-V` with a lower-casing function, raise a `TypeError` when parsing
instead of one silently making the other unreachable. This includes the on
and off names of a boolean flag, such as `-s/-S`.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a note about fixing --level=-2 kind of option value that have a dash in their string. This is related to #2871 and #2676.

Ah, maybe we should add test coverage for these cases:

  • --level=-2
  • -l-2
  • --level -2

Comment thread src/click/core.py
elif token[:2] in tables.opt_prefixes:
# long prefix, no matching long opt
if not ctx.ignore_unknown_options:
raise NoSuchOption(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An option here with a str.lower normalizer does not suggest an option.

This test fail on this PR:

@pytest.mark.parametrize(
    ("args", "expect"),
    [
        pytest.param(["--RIPPE"], "Did you mean '--ripe'?", id="option"),
        pytest.param(["PEEEL"], "Did you mean 'peel'?", id="command"),
    ],
)
def test_normalization_suggestion(runner, args, expect):
    @click.group(context_settings=CONTEXT_SETTINGS)
    @click.option("--ripe", is_flag=True)
    def cli(ripe):
        pass

    @cli.command()
    def peel():
        pass

    result = runner.invoke(cli, args)
    assert expect in result.output

Comment thread src/click/core.py

if value is not UNSET and not self.multiple:
# Use only the last occurrence of the option if multiple isn't enabled.
value = value[-1]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test does not pass on this PR but works on main and shows that a custom option redefining handle_parse_result does not work when reading or writing a single value:

@pytest.mark.parametrize(
    ("rewrite", "args", "expect"),
    [
        pytest.param(lambda value: "kiwi", [], "kiwi", id="write"),
        pytest.param(
            lambda value: value.upper(),
            ["--fruit", "kiwi"],
            "KIWI",
            id="read-and-write",
        ),
    ],
)
def test_handle_parse_result_rewrites_opts(runner, rewrite, args, expect):
    class RewriteOption(click.Option):
        def handle_parse_result(self, ctx, opts, args):
            opts = {**opts, self.name: rewrite(opts.get(self.name))}
            return super().handle_parse_result(ctx, opts, args)

    @click.command()
    @click.option("--fruit", cls=RewriteOption)
    def cli(fruit):
        return fruit

    result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)
    assert result.return_value == expect

I know that both handle_parse_result and consume_value are marked :meta private: so I am OK to change the behavior. Just maybe a good idea to lock it down with these kind of tests.

Comment thread CHANGES.md
`split_opt`. `split_arg_string` is available as
{func}`click.split_arg_string`.
Use `optparse` from the standard library if you need the old parser.
- `Command.make_parser` and `Parameter.add_to_parser` are removed.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should add a deprecation warning for that in 8.6.0 ?

Comment thread src/click/core.py
# No more tokens, but the current opt still required a value.
assert looking_opt is not None and looking_opt_name is not None
message = ngettext(
"Option {name!r} requires a value.",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah! That's a better error message! :) Should we add an entry to inform users of that change in the changelog?

This branch has not been deployed

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

Labels

parsing Parsing, parameters, commands, chaining, context

Projects

None yet

2 participants