Skip to content

Fix error message for unrecognized multicharacter short options#3253

Closed
lfshao wants to merge 1 commit intopallets:mainfrom
lfshao:fix/multichar-short-option-error-message
Closed

Fix error message for unrecognized multicharacter short options#3253
lfshao wants to merge 1 commit intopallets:mainfrom
lfshao:fix/multichar-short-option-error-message

Conversation

@lfshao
Copy link

@lfshao lfshao commented Mar 7, 2026

Fixes #2779

When a multicharacter short option like -dbg is registered (e.g., @click.option("-dbg", is_flag=True)), the parser correctly handles it by treating it as a long-style option with a single-dash prefix. However, when an unrecognized variant like -dbgwrong is passed:

  1. _match_long_opt fails because -dbgwrong is not a registered option.
  2. The parser falls back to _match_short_opt, which iterates character by character.
  3. Since -d is not a registered short option either, it raises NoSuchOption("-d").

This yields the confusing error: No such option: -d instead of No such option: -dbgwrong.

Fix

In _process_opts, wrap the _match_short_opt fallback in a try/except. If NoSuchOption is raised for the very first character of the arg (i.e., the short-option parser never made any progress), re-raise with the full original option name instead.

This preserves correct behaviour for normal short option combinations: if -d and -b are registered but -g is not, passing -dbg still correctly reports No such option: -g.

Changes

  • src/click/parser.py: Catch NoSuchOption from the short-option fallback and re-raise with the full option name when the first character itself is unknown.
  • tests/test_parser.py: Add regression test for the fixed behaviour.
  • CHANGES.rst: Add changelog entry.

When a multicharacter short option like `-dbg` is registered and an
unrecognized variant like `-dbgwrong` is passed, the parser first tries
a long-option match (which fails), then falls back to character-by-character
short-option matching. If the first character itself is not a known short
option, the error previously reported only that character (e.g. `-d`)
instead of the full original argument.

Fix this by catching NoSuchOption in _process_opts when the short-option
fallback fails on the very first character, and re-raising with the full
original option name.

Fixes pallets#2779
@davidism davidism closed this Mar 7, 2026
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.

Wrong error message when wrong multicharacter short option is passed

2 participants