Skip to content

Simplify float stat conversion using Pydantic coercion #340

Description

@Mattsface

Summary

PR #241 adds a custom BeforeValidator / OptionalFloat type to convert MLB Stats API string values such as ".287" into Python floats.

Pydantic already performs this coercion for fields typed as float or Optional[float] (float | None), so the custom conversion logic is unnecessary for normal numeric strings.

Related PR: #241

Proposed change

Replace uses of the custom OptionalFloat type with standard Pydantic annotations, for example:

avg: Optional[float] = None
ops: Optional[float] = None
slg: Optional[float] = None

Pydantic will convert values such as:

".287" -> 0.287
"1.024" -> 1.024

without a custom validator.

MLB sentinel values

Before removing the validator entirely, verify whether the MLB Stats API can return non-numeric sentinel values for these fields, such as:

.---
-
""

If those values occur, normalization should handle only those MLB-specific sentinel values and allow Pydantic to perform the normal string-to-float coercion.

We should avoid silently converting every invalid value to None, since that can hide unexpected API data or model errors.

Acceptance criteria

  • Verify representative MLB responses for numeric float fields and identify any sentinel/non-numeric values.
  • Replace OptionalFloat with Optional[float] / float | None where standard Pydantic coercion is sufficient.
  • Remove the generic float_or_none / BeforeValidator conversion if it is no longer needed.
  • If MLB sentinel values require normalization, handle only the known sentinel values explicitly.
  • Add or update tests covering numeric strings, None, and any known MLB sentinel values.
  • Ensure the full test suite passes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions