litestar-org/polyfactory

Bug: Attribute with `_` prefixed alias cannot be set on a factory class

uhlikfil opened this issue · 4 comments

Description

When a model has an attribute, that is not private, but its alias is prefixed with an underscore (because of e.g. third party input data format), it is not generated by the model's factory, nor it can have a default set as a model attribute.

URL to code causing the issue

No response

MCVE

import uuid

from polyfactory import Use
from polyfactory.factories.pydantic_factory import ModelFactory
from pydantic import BaseModel, Field


class A(BaseModel):
    id_field: str = Field(..., alias="_id")


class AFactory(ModelFactory[A]):
    __model__ = A

    _id = Use(lambda: str(uuid.uuid4()))
    # id_field = Use(... doesn't work either

a = AFactory.build()

Steps to reproduce

No response

Screenshots

No response

Logs

No response

Release Version

2.11.0

Platform

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

Note

While we are open for sponsoring on GitHub Sponsors and
OpenCollective, we also utilize Polar.sh to engage in pledge-based sponsorship.

Check out all issues funded or available for funding on our Polar.sh Litestar dashboard

  • If you would like to see an issue prioritized, make a pledge towards it!
  • We receive the pledge once the issue is completed & verified
  • This, along with engagement in the community, helps us know which features are a priority to our users.
Fund with Polar
guacs commented

Overriding the should_set_field_value on the factory should work. Here's the relevant reference docs.

guacs commented

@uhlikfil I'm going to close this for now, but feel free to reopen it if the solution given above does not work.

@guacs Thank you for the workaround.

A question: Is this just not implemented, requiring an ugly workaround, or is there a reason to avoid supporting aliases that start with _ (e.g. alias="_id")? In the first case we can keep the issue open so someone can submit a PR.

@olk-m it's not a workaround. You're meant to override the should_set_field_value class method if you want behavior different from the default.

Also, it's not that it doesn't support aliases prefixed with _, it's that the default behavior is to not include private members of a given model. So if you have any field that's prefixed with _, they will be ignored. Now if you're asking as to why that is default behavior, I'm actually not sure. However, we can't change it now since that would be a breaking change.