litestar-org / litestar-org/polyfactory
Bug: unexpected behavior with `seed_random`
- Dominant language
- Python
- Stars
- 1.5k
- Forks
- 120
- PR merge metrics
- No merged PRs in 30d
Description
```python
name = Use(ModelFactory.__random__.choice, ["rule", "group_rule", "misc_rule"])
color = Use(ModelFactory.__random__.choice, ["green", "red", "purple"])
type = Use(ModelFactory.__random__.choice, ["input", "checkbox", "list", "link"])
```
shouldn't `ModelFactory.seed_random(10)` make the above work?
it only works doing like @Alc-Alc said
```python
name = lambda: RuleFactory.__random__.choice(["rule", "group_rule", "misc_rule"])
color = lambda: RuleFactory.__random__.choice(["green", "red", "purple"])
type = lambda: RuleFactory.__random__.choice(["input", "checkbox", "list", "link"])
```
But this gives an warning: https://docs.astral.sh/ruff/rules/lambda-assignment/ and it's a little bit _ugly_.
_Originally posted by @JobaDiniz in https://github.com/litestar-org/polyfactory/discussions/578#discussioncomment-10366326_
The use of `Use` doesn't result in deterministic behavior even if one calls `BaseFactory.seed_random(some_seed)`. This is due to how we're implementing seed_random. We create a new Random instance with the given seed instead of reseeding the existing instance. This means that the cls.__random__.choice function that's referenced is the method associated with the Random instance before we call seed_random. Thus, you don't get the deterministic behavior.
This should be fixed so that `seed_instance` reseeds the existing random instance we have instead of creating a new one.
Contributor guide
Research direction
Start by locating the implementation of BaseFactory.seed_random and seed_instance, then trace how Use stores the referenced random method. Add a regression test covering seeded choices through Use and verify that repeated runs with the same seed produce identical values without requiring lambdas.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- testing-qa
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100