polyfactory icon indicating copy to clipboard operation
polyfactory copied to clipboard

feat: optionally pass args to provider function

Open iloveitaly opened this issue 9 months ago • 4 comments

Description

Right now, a provider has no context about the class or field in question. Most of the time, that's fine.

In my scenario, I am generating TypeIDs which are prefixed with a specific string tied to a particular field name (more details. This requires the context of the field and model to determine a good random ID.

This change passes in the model and field meta into the provider, if the provider function accepts the right arguments with the right names.

Closes

iloveitaly avatar Mar 24 '25 19:03 iloveitaly

Can should_use_default_value be overriden at the factory level instead? If always use a default for this type then should handle this case https://github.com/litestar-org/polyfactory/blob/main/polyfactory/factories/base.py#L951-L963

adhtruong avatar Mar 24 '25 20:03 adhtruong

@adhtruong if the default value isn't used, how is the field generated? I don't understand that part of the logic yet.

iloveitaly avatar Mar 24 '25 22:03 iloveitaly

Sorry, I believe I misunderstood this use case.

Guessing this is not expressible in python type system currently? This feels like a specific use case that should be pushed to custom base factory by overriding get_field_value itself if possible

adhtruong avatar Mar 25 '25 21:03 adhtruong

Guessing this is not expressible in python type system currently? T

Nope, it's not, since the generated value is dependent on an instance of TypeID specific to that field. You need both the class + field reference in order to pull the right generator from the model config.

This feels like a specific use case that should be pushed to custom base factory by overriding get_field_value itself if possible

Yeah, could definitely see this as something specific to my app, although I'm curious if others have run into a similar problem where a type provider needs context of the class in question to generate a good result.

iloveitaly avatar Mar 26 '25 21:03 iloveitaly