Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Random values from a base Enum #640

Open
1 of 4 tasks
sander76 opened this issue Feb 7, 2025 · 2 comments
Open
1 of 4 tasks

Bug: Random values from a base Enum #640

sander76 opened this issue Feb 7, 2025 · 2 comments
Labels
bug Something isn't working

Comments

@sander76
Copy link

sander76 commented Feb 7, 2025

Description

I don't think it's a bug, but not sure:

Consider this example:

from dataclasses import dataclass
from enum import Enum

from polyfactory.factories import DataclassFactory

class BaseEnum(Enum): ...


class OtherEnum(BaseEnum):  # <--- inherits from BaseEnum
    VALUE_1 = 1
    VALUE_2 = 2


@dataclass
class MyModel:
    values: dict[BaseEnum, int]  # <--- a dict with keys from the BaseEnum


class MyModelFactory(DataclassFactory[MyModel]): ...


if __name__ == "__main__":
    my_model = MyModelFactory.build()

This will raise an IndexError: IndexError: Cannot choose from an empty sequence.
Which is obvious as Litestar will try to populate the keys in the values dict by doing this: __random__(list(BaseEnum)). That results in an empty list which gives the error.

But the BaseEnum (which I don't have control over) is only the base enum for the OtherEnum which does contain values.

Is there any way in my factory to tell when BaseEnum is encountered it should pick values from OtherEnum ?

URL to code causing the issue

No response

MCVE

Steps to reproduce

Run the above example.

Screenshots

Logs

Release Version

2.19.0

Platform

  • Linux
  • Mac
  • Windows
  • Other (Please specify in the description above)
@sander76 sander76 added the bug Something isn't working label Feb 7, 2025
@nisemenov
Copy link
Contributor

Hi!
If you can not do something like this:

class MyModel:
    values: dict[OtherEnum, int]

Maybe this decision will suit you?
Any of Use(), lambda or @classmethod.

@sander76
Copy link
Author

sander76 commented Feb 7, 2025

I think you mean I explicity/manually fill the values dictionary?.
I could do that, but my problem is that my real data is really nested and that would require me to do the manual filling in a lot of places.

I have indeed no control of the shape of my model. So

class MyModel:
    values: dict[OtherEnum, int]

is not possible unfortunately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants