Skip to content

fix(msgspec): handle boolean tz constraint from Meta#842

Open
tysoncung wants to merge 1 commit into
litestar-org:mainfrom
tysoncung:fix/768-msgspec-datetime-tz
Open

fix(msgspec): handle boolean tz constraint from Meta#842
tysoncung wants to merge 1 commit into
litestar-org:mainfrom
tysoncung:fix/768-msgspec-datetime-tz

Conversation

@tysoncung
Copy link
Copy Markdown

Problem

When using msgspec.Meta(tz=True) with a datetime field, polyfactory crashes with a TypeError because handle_constrained_date receives a bool for the tz parameter but expects a tzinfo object.

Closes #768

Reproduction

from datetime import datetime
from typing import Annotated

from msgspec import Struct, Meta
from polyfactory.factories.msgspec_factory import MsgspecFactory


class SomeStruct(Struct):
    some_datetime: Annotated[datetime, Meta(tz=True)]


class SomeStructFactory(MsgspecFactory[SomeStruct]): ...

SomeStructFactory.build()  # TypeError!

Solution

In handle_constrained_date, convert boolean tz values before using them:

  • Truetimezone.utc (timezone-aware datetime)
  • FalseNone (falls back to UTC default)

This is a minimal, targeted fix in polyfactory/value_generators/constrained_dates.py.

Changes

File Change
polyfactory/value_generators/constrained_dates.py Update tz type hint to accept bool, convert boolean values before use

msgspec's Meta(tz=True) passes a bool for the tz parameter, but
handle_constrained_date expected a tzinfo object. This caused a
TypeError when building structs with Annotated[datetime, Meta(tz=True)].

Convert boolean tz values: True -> timezone.utc, False -> None.

Closes litestar-org#768
@tysoncung tysoncung requested a review from adhtruong as a code owner March 24, 2026 14:53
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: date value generator incompatible with masgspec datetime 'tz' constraint

1 participant