polyfactory
polyfactory copied to clipboard
Bug: Incorrect generation on literal values
Description
When a pydantic model has a field that is a union of literals, the factory doesn't generate correct values
URL to code causing the issue
No response
MCVE
from typing import Literal
from polyfactory.factories.pydantic_factory import ModelFactory
from pydantic import BaseModel
type MyFieldType = Literal["a"] | Literal["b"]
class MyModel(BaseModel):
my_field: MyFieldType
class MyModelFactory(ModelFactory[MyModel]):
pass
MyModelFactory.build()
Steps to reproduce
run the MCVE
Screenshots
"In the format of: "
Logs
venv/bin/python my_file.py
venv/lib/python3.14/site-packages/polyfactory/factories/pydantic_factory.py:86: UserWarning: Core Pydantic V1 functionality isn't compatible with Python 3.14 or greater.
import pydantic.v1 as pydantic_v1 # type: ignore[no-redef]
Traceback (most recent call last):
File "my_file.py", line 15, in <module>
MyModelFactory.build()
~~~~~~~~~~~~~~~~~~~~^^
File "venv/lib/python3.14/site-packages/polyfactory/factories/pydantic_factory.py", line 548, in build
return cls._create_model(kwargs["_build_context"], **processed_kwargs)
~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "venv/lib/python3.14/site-packages/polyfactory/factories/pydantic_factory.py", line 577, in _create_model
return cls.__model__(**kwargs)
~~~~~~~~~~~~~^^^^^^^^^^
File "venv/lib/python3.14/site-packages/pydantic/main.py", line 250, in __init__
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
pydantic_core._pydantic_core.ValidationError: 2 validation errors for MyModel
my_field.literal['a']
Input should be 'a' [type=literal_error, input_value=typing.Literal['a'], input_type=_LiteralGenericAlias]
For further information visit https://errors.pydantic.dev/2.12/v/literal_error
my_field.literal['b']
Input should be 'b' [type=literal_error, input_value=typing.Literal['a'], input_type=_LiteralGenericAlias]
For further information visit https://errors.pydantic.dev/2.12/v/literal_error
Release Version
3.0.0
Platform
- [ ] Linux
- [x] Mac
- [ ] Windows
- [ ] Other (Please specify in the description above)
Thanks for reporting.
This seems like a 3.14 specific bug due to https://docs.python.org/3/whatsnew/3.14.html#typing and handling of union representation. polyfactory doesn't support 3.14 officially yet so may run into edge cases like this but looking to support soon