litestar-org / litestar-org/polyfactory

Enhancement: Support custom provider on types created through 3.14 type statements

Open
#853 1 comment 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Python
Stars
1.5k
Forks
120
PR merge metrics
No merged PRs in 30d

Description

### Summary

Python 3.14 added type aliases through type statements: https://docs.python.org/3/library/typing.html#type-aliases
These aliases are preserved in the annotations:
```python
type ConstrainedString = Annotated[str, pydantic.AfterValidator(validator)]
ConstrainedStringOld = Annotated[str, pydantic.AfterValidator(validator)]
print(repr(ConstrainedString | None)) # ConstrainedString | None
print(repr(ConstrainedStringOld | None)) # typing.Optional[typing.Annotated[str, AfterValidator(func= str:
if len(value) % 2 == 0:
raise ValueError("Must be an odd length string")
return value

type ConstrainedString = Annotated[str, pydantic.AfterValidator(validator)]

ModelFactory.add_provider(ConstrainedString, lambda: "f" + "oo" * ModelFactory.__random__.randint(0,100))

class MyModel(pydantic.BaseModel):
s: ConstrainedString

class MyModelFactory(ModelFactory[MyModel]):
__check_model__ = True

# Neither of these work
print(list(MyModelFactory.coverage()))
print(list(MyModelFactory.batch(10)))

class MyModelWithNone(pydantic.BaseModel):
s: ConstrainedString | None

class MyModelWithNoneFactory(ModelFactory[MyModelWithNone]):
__check_model__ = True

print(list(MyModelWithNoneFactory.coverage())) # Surprisingly works
print(list(MyModelWithNoneFactory.batch(10))) # But this doesn't work
```

### Drawbacks and Impact

_No response_

### Unresolved questions

_No response_

Contributor guide

Open the contributing guide

Research direction

Start by tracing ModelFactory.add_provider and how coverage() and batch() resolve the ConstrainedString and ConstrainedString | None annotations shown in the example. Compare the behavior of the Python 3.14 type statement with the older Annotated alias, then verify that custom providers are used for both direct and optional fields.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.