Skip to content

Handle ValueError for missing format keys - #212

Open
cpruijsen wants to merge 1 commit into
fluent:masterfrom
cpruijsen:fix/issue-189
Open

cpruijsen wants to merge 1 commit into
fluent:masterfrom
cpruijsen:fix/issue-189

Conversation

@cpruijsen

Copy link
Copy Markdown

Catch (KeyError, ValueError) in _format_by_dict so FluentRecordFormatter(fill_missing_fmt_key=True) fills missing { and $ style fields with None on Python 3.8+. Since Python 3.8, logging.StrFormatStyle / StringTemplateStyle wrap a missing field as ValueError instead of KeyError (python/cpython#79025). _format_by_dict only caught KeyError, so the fill flag did nothing for those styles. % style was already handled because it still uses value % record.__dict__.

Fixes #189

Decision

Catch (KeyError, ValueError) in the existing handler, as asked in the issue ("ValueError must be handled here"). The other option is to treat ValueError as a missing key only when __context__ is KeyError, so an invalid format spec (e.g. {name:d} on a str) still raises when fill_missing_fmt_key=True. _format_by_dict already uses a bare type catch; the flag is opt-in; inspecting __context__ is more clever than the rest of handler.py. Can switch to the narrower match.

Test plan

  • pytest tests/test_handler.py (20 passed, including new {/$ fill tests)
  • New tests fail on unfixed _format_by_dict (ValueError: Formatting field not found in record: 'custom_field'), each in isolation
  • pytest tests/test_asynchandler.py (15 passed; formatter is shared)
  • CI: Python 3.7-3.12 / PyPy (3.7 still raises KeyError for {/$; both types are caught)

Python 3.8+ logging { and $ styles raise ValueError instead of
KeyError, so fill_missing_fmt_key=True never filled those keys.


Signed-off-by: Christopher Pruijsen <christopher.pruijsen@gmail.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.

Formatting exception handling and fill_missing_fmt_key error

1 participant