Skip to content

Fix Enum option value lost when callback is used#1554

Open
Fridayai700 wants to merge 1 commit intofastapi:masterfrom
Fridayai700:fix-enum-callback-223
Open

Fix Enum option value lost when callback is used#1554
Fridayai700 wants to merge 1 commit intofastapi:masterfrom
Fridayai700:fix-enum-callback-223

Conversation

@Fridayai700
Copy link

Type of changes

  • Bug fix

AI?

  • AI was used to generate this PR

Checklist

  • I've run the latest black with default args on new code.
  • I've updated CHANGELOG.md and CONTRIBUTORS.md where appropriate (see note about typos above).
  • I've added tests for new code.
  • I accept that @willmcgugan may be pedantic in the code review.

Description

Fixes #223

When a typer.Option has both a callback and an Enum type, the callback executes correctly but the command function receives None instead of the Enum value.

Root cause: The generate_enum_convertor in typer/main.py converts values by calling str(value) and looking up the result in a map of {str(enum.value): enum_member}. When a callback returns an Enum instance, str(EndpointChoices.localhost) produces "EndpointChoices.localhost", which doesn't match any key in the map (keys are "localhost", "staging", etc.). The convertor returns None.

Fix: Add an early return in the enum convertor: if the value is already an instance of the target enum, return it directly instead of trying to convert it again.

Test added: test_enum_with_callback — verifies that an Enum option with a callback correctly passes the Enum value to the command function. Confirmed the test fails without the fix ('NoneType' object has no attribute 'value') and passes with it.

Closes fastapi#223

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
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.

[BUG] callback with type Enum passes None back to the app command

1 participant

Comments