litestar-org/polyfactory

Union types of models don't unwrap correctly

AvivSamet-Silk opened this issue · 3 comments

Description

Trying to build a pydantic factory that has union types of other pydantic factories causes an error.

URL to code causing the issue

No response

MCVE

# Your MCVE code here

class A(BaseModel):
    a: str

class B(BaseModel):
    b: Union[list[A] | A] = Field(...)

class BFactory(ModelFactory[B]):
    __model__ = B

if __name__ == '__main__':
    factory = Bfactory()
    factory.build()

Steps to reproduce

1. Paste the above code plus relative import
2. Run code

Screenshots

"In the format of: ![SCREENSHOT_DESCRIPTION](SCREENSHOT_LINK.png)"
image

Logs

No response

Litestar Version

polyfactory version 2.5.0

Platform

  • Linux
  • Mac
  • Windows
  • Other (Please specify in the description above)

Funding

  • You can sponsor this specific effort via a Polar.sh pledge below
  • We receive the pledge once the issue is completed & verified
Fund with Polar

Hi Aviv,

What python version are you using?

I am using python 3.10

There is no problem on our end, the issue is with your code, please rewrite the above like so:

    class A(BaseModel):
        a: str

    class B(BaseModel):
        b: list[A] | A

    class BFactory(ModelFactory[B]):
        __model__ = B

    assert BFactory.build()

You issues are as follow:

  1. you wrap a union inside another union: Union[list[A] | A] = Field(...), rewrite this as: list[A] | A
  2. You are instantiating the factory, which you shouldnt do:
    factory = Bfactory()
    factory.build()

rewrite this as:

BFactory.build()

All factory methods are class methods and do not depend on instantiation.