The post_generated decorator#

The post_generated decorator wraps a classmethod into a PostGenerated field. This is useful when the post generated field depends on the current factory, usually its __faker__ and/or __random__ attribute. For example:

Using the post_generated decorator#
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import cast

from polyfactory.decorators import post_generated
from polyfactory.factories import DataclassFactory


@dataclass
class DatetimeRange:
    to_dt: datetime
    from_dt: datetime = field(default_factory=datetime.now)


class DatetimeRangeFactory(DataclassFactory[DatetimeRange]):
    @post_generated
    @classmethod
    def to_dt(cls, from_dt: datetime) -> datetime:
        return from_dt + cast(timedelta, cls.__faker__.time_delta("+3d"))


def test_post_generated() -> None:
    date_range_instance = DatetimeRangeFactory.build()
    assert date_range_instance.to_dt > date_range_instance.from_dt
    assert date_range_instance.to_dt < date_range_instance.from_dt + timedelta(days=3)

All classmethod parameters after cls must be named as the fields this post generated field depends on.