### Install Polyfactory with pip Source: https://polyfactory.litestar.dev/latest/getting-started.html Install the polyfactory library using pip. ```bash pip install polyfactory ``` -------------------------------- ### FieldMeta.parse_examples Source: https://polyfactory.litestar.dev/latest/reference/field_meta.html Get the example values from the given annotation metadata. ```APIDOC ## FieldMeta.parse_examples ### Description Get the example values from the given annotation metadata. Any metadata object with a non-empty `examples` list attribute is supported, e.g. `msgspec.Meta` or `pydantic.Field`. If several are given, the last one wins. ### Method Classmethod ### Signature `parse_examples(metadata: Sequence[Any]) -> list[Any] | None` ### Parameters - **metadata** (Sequence[Any]) - Required - A list of annotation metadata. ### Returns list[Any] | None - A list of example values, if any. ``` -------------------------------- ### Install dependencies with uv sync Source: https://polyfactory.litestar.dev/latest/contribution-guide.html Creates a virtual environment and installs all dependencies including extras. Required before running the documentation server or build. ```bash uv sync --all-extras ``` -------------------------------- ### get_args function implementation and docstring examples Source: https://polyfactory.litestar.dev/latest/_modules/typing.html Implementation of get_args with docstring examples showing usage with Dict, Union, Tuple, and Callable. ```python >>> T = TypeVar('T') >>> assert get_args(Dict[str, int]) == (str, int) >>> assert get_args(int) == () >>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str) >>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) >>> assert get_args(Callable[[], T][int]) == ([], int) ``` ```python def get_args(tp): """Get type arguments with all substitutions performed. For unions, basic simplifications used by Union constructor are performed. Examples:: >>> T = TypeVar('T') >>> assert get_args(Dict[str, int]) == (str, int) >>> assert get_args(int) == () >>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str) >>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) >>> assert get_args(Callable[[], T][int]) == ([], int) """ if isinstance(tp, _AnnotatedAlias): return (tp.__origin__,) + tp.__metadata__ if isinstance(tp, (_GenericAlias, GenericAlias)): res = tp.__args__ if _should_unflatten_callable_args(tp, res): res = (list(res[:-1]), res[-1]) return res if isinstance(tp, types.UnionType): return tp.__args__ return () ``` -------------------------------- ### is_typeddict function implementation and docstring example Source: https://polyfactory.litestar.dev/latest/_modules/typing.html Implementation of is_typeddict with a docstring example showing a TypedDict class and checking it. ```python >>> from typing import TypedDict >>> class Film(TypedDict): ... title: str ... year: int ... >>> is_typeddict(Film) True >>> is_typeddict(dict) False ``` ```python def is_typeddict(tp): """Check if an object is a TypedDict class. For example:: >>> from typing import TypedDict >>> class Film(TypedDict): ... title: str ... year: int ... >>> is_typeddict(Film) True >>> is_typeddict(dict) False """ return isinstance(tp, _TypedDictMeta) ``` -------------------------------- ### should_use_example_value method Source: https://polyfactory.litestar.dev/latest/_modules/polyfactory/factories/base.html Determines whether to use a random example value for a field, based on __use_examples__ and the presence of examples. ```python return cls.__use_examples__ and bool(field_meta.examples) ``` -------------------------------- ### SQLAlchemy example: Pre-fetch async data for factory fields Source: https://polyfactory.litestar.dev/latest/usage/fields.html Complete example showing how to pre-fetch data asynchronously (e.g., from a database) and pass the resolved value as a regular argument to the factory. It defines SQLAlchemy models, factories, and a test that creates a department with a director_id fetched asynchronously. ```python from __future__ import annotations from sqlalchemy import ForeignKey, select from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory async_engine = create_async_engine("sqlite+aiosqlite:///:memory:") class Base(DeclarativeBase): ... class User(Base): __tablename__ = "users" id: Mapped[int] = mapped_column(primary_key=True) class Department(Base): __tablename__ = "departments" id: Mapped[int] = mapped_column(primary_key=True) director_id: Mapped[str] = mapped_column(ForeignKey("users.id")) class UserFactory(SQLAlchemyFactory[User]): ... class DepartmentFactory(SQLAlchemyFactory[Department]): ... async def get_director_ids() -> int: async with AsyncSession(async_engine) as session: result = (await session.scalars(select(User.id))).all() return UserFactory.__random__.choice(result) async def test_factory_with_pre_fetched_async_data() -> None: async with async_engine.begin() as conn: await conn.run_sync(Base.metadata.drop_all) await conn.run_sync(Base.metadata.create_all) async with AsyncSession(async_engine) as session: UserFactory.__async_session__ = session await UserFactory.create_batch_async(3) async with AsyncSession(async_engine) as session: DepartmentFactory.__async_session__ = session department = await DepartmentFactory.create_async(director_id=await get_director_ids()) user = await session.scalar(select(User).where(User.id == department.director_id)) assert isinstance(user, User) ``` -------------------------------- ### Parse example values from metadata in parse_examples Source: https://polyfactory.litestar.dev/latest/_modules/polyfactory/field_meta.html The `parse_examples` class method scans annotation metadata for objects with a non-empty `examples` list attribute (e.g., `msgspec.Meta` or `pydantic.Field`). If multiple are found, the last one wins. Returns a list of example values or `None`. ```python @classmethod def parse_examples(cls, metadata: Sequence[Any]) -> list[Any] | None: """Get the example values from the given annotation metadata. Any metadata object with a non-empty ``examples`` list attribute is supported, e.g. ``msgspec.Meta`` or ``pydantic.Field``. If several are given, the last one wins. :param metadata: A list of annotation metadata. :returns: A list of example values, if any. """ examples = None for value in metadata: if isinstance(value_examples := getattr(value, "examples", None), list) and value_examples: examples = value_examples return examples ``` -------------------------------- ### Get configuration dictionary for factory Source: https://polyfactory.litestar.dev/latest/_modules/polyfactory/factories/base.html Builds a configuration dictionary by retrieving attributes listed in __config_keys__ and adding the provider map under '_extra_providers'. ```python return { **{key: getattr(cls, key) for key in cls.__config_keys__}, "_extra_providers": cls.get_provider_map(), } ``` -------------------------------- ### BaseFactory.should_use_example_value(field_meta: FieldMeta) -> bool Source: https://polyfactory.litestar.dev/latest/reference/factories/base.html Classmethod that determines whether to use a random example value for the given field. ```APIDOC ## should_use_example_value(field_meta: FieldMeta) -> bool ### Description Determine whether to use a random example value for the given field. ### Parameters - **field_meta** (FieldMeta) - FieldMeta instance. ### Notes - This method is distinct to allow overriding. ### Returns A boolean determining whether an example value should be used for the given field_meta. ``` -------------------------------- ### Use Examples Values with Pydantic ModelFactory Source: https://polyfactory.litestar.dev/latest/usage/configuration.html Set `__use_examples__ = True` to use a random value from the field's `examples` list. The default is `False`. Override `should_use_example_value()` for finer control. Examples are read from Pydantic's `Field(examples=...)` (Pydantic >= V2). ```python from pydantic import BaseModel, Field from polyfactory.factories.pydantic_factory import ModelFactory class Payment(BaseModel): amount: int = Field(0) currency: str = Field(examples=["USD", "EUR", "INR"]) class PaymentFactory(ModelFactory[Payment]): __use_examples__ = True def test_use_examples() -> None: instance = PaymentFactory.build() assert instance.currency in ["USD", "EUR", "INR"] ``` -------------------------------- ### get_origin function implementation and docstring examples Source: https://polyfactory.litestar.dev/latest/_modules/typing.html Implementation of get_origin with docstring examples showing usage with ParamSpec, Literal, ClassVar, Generic, Union, List, and P.args. ```python >>> P = ParamSpec('P') >>> assert get_origin(Literal[42]) is Literal >>> assert get_origin(int) is None >>> assert get_origin(ClassVar[int]) is ClassVar >>> assert get_origin(Generic) is Generic >>> assert get_origin(Generic[T]) is Generic >>> assert get_origin(Union[T, int]) is Union >>> assert get_origin(List[Tuple[T, T]][int]) is list >>> assert get_origin(P.args) is P ``` ```python def get_origin(tp): """Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, ClassVar, Annotated, and others. Return None for unsupported types. Examples:: >>> P = ParamSpec('P') >>> assert get_origin(Literal[42]) is Literal >>> assert get_origin(int) is None >>> assert get_origin(ClassVar[int]) is ClassVar >>> assert get_origin(Generic) is Generic >>> assert get_origin(Generic[T]) is Generic >>> assert get_origin(Union[T, int]) is Union >>> assert get_origin(List[Tuple[T, T]][int]) is list >>> assert get_origin(P.args) is P """ if isinstance(tp, _AnnotatedAlias): return Annotated if isinstance(tp, (_BaseGenericAlias, GenericAlias, ParamSpecArgs, ParamSpecKwargs)): return tp.__origin__ if tp is Generic: return Generic if isinstance(tp, types.UnionType): return types.UnionType return None ``` -------------------------------- ### Minimal dataclass factory example Source: https://polyfactory.litestar.dev/latest/getting-started.html Defines a Person dataclass and a DataclassFactory subclass to generate mock data. The factory uses type hints to build a Person instance with correct types. ```python from dataclasses import dataclass from polyfactory.factories import DataclassFactory @dataclass class Person: name: str age: float height: float weight: float class PersonFactory(DataclassFactory[Person]): __model__ = Person def test_is_person() -> None: person_instance = PersonFactory.build() assert isinstance(person_instance, Person) assert isinstance(person_instance.name, str) assert isinstance(person_instance.age, float) assert isinstance(person_instance.height, float) assert isinstance(person_instance.weight, float) ``` -------------------------------- ### SQLAlchemy factory module imports and setup Source: https://polyfactory.litestar.dev/latest/_modules/polyfactory/factories/sqlalchemy_factory.html Imports required for the SQLAlchemy factory, including optional SQLAlchemy imports with a MissingDependencyException if not installed. Also defines the T type variable. ```python from __future__ import annotations import enum from collections.abc import Awaitable, Collection, Mapping from dataclasses import is_dataclass from datetime import date, datetime from typing import ( TYPE_CHECKING, Annotated, Any, Callable, ClassVar, Generic, Protocol, TypeVar, Union, cast, ) from sqlalchemy.util.langhelpers import duck_type_collection from polyfactory.exceptions import ConfigurationException, MissingDependencyException, ParameterException from polyfactory.factories.base import BaseFactory from polyfactory.factories.base import BuildContext as BaseBuildContext from polyfactory.field_meta import Constraints, FieldMeta from polyfactory.persistence import AsyncPersistenceProtocol, SyncPersistenceProtocol from polyfactory.utils.types import Frozendict try: from sqlalchemy import ARRAY, Column, Numeric, String, inspect, types from sqlalchemy.dialects import mssql, mysql, postgresql, sqlite from sqlalchemy.exc import NoInspectionAvailable from sqlalchemy.ext.associationproxy import AssociationProxy from sqlalchemy.ext.asyncio import async_scoped_session from sqlalchemy.orm import InstanceState, Mapper, RelationshipProperty, scoped_session, sessionmaker except ImportError as e: msg = "sqlalchemy is not installed" raise MissingDependencyException(msg) from e if TYPE_CHECKING: from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker from sqlalchemy.orm import Session from sqlalchemy.sql.type_api import TypeEngine from typing_extensions import NotRequired, TypeGuard else: try: from sqlalchemy.ext.asyncio import async_sessionmaker except ImportError: async_sessionmaker = sessionmaker T = TypeVar("T") ``` -------------------------------- ### Initialize model and validate support Source: https://polyfactory.litestar.dev/latest/_modules/polyfactory/factories/base.html Sets the model from __model__ or infers it, raising ConfigurationException if missing or unsupported. Suggests subclassing the appropriate base factory. ```python @classmethod def _init_model(cls) -> None: model: type[T] | None = getattr(cls, "__model__", None) or cls._infer_model_type() if not model: msg = f"required configuration attribute '__model__' is not set on {cls.__name__}" raise ConfigurationException( msg, ) cls.__model__ = model if not cls.is_supported_type(model): for factory in BaseFactory._base_factories: if factory.is_supported_type(model): msg = f"{cls.__name__} does not support {model.__name__}, but this type is supported by the {factory.__name__} base factory class. To resolve this error, subclass the factory from {factory.__name__} instead of {cls.__name__}" raise ConfigurationException( msg, ) msg = f"Model type {model.__name__} is not supported. To support it, register an appropriate base factory and subclass it for your factory." raise ConfigurationException( msg, ) ``` -------------------------------- ### NoReturn example: function that never returns Source: https://polyfactory.litestar.dev/latest/_modules/typing.html Shows a function annotated with NoReturn that always raises an exception. NoReturn can also be used as a bottom type; starting in Python 3.11, Never should be used instead. ```python from typing import NoReturn def stop() -> NoReturn: raise Exception('no way') ``` -------------------------------- ### Using flush() vs commit() for persistence with SQLAlchemyPersistenceMethod.FLUSH Source: https://polyfactory.litestar.dev/latest/usage/library_factories/sqlalchemy_factory.html Configures the factory to use `flush()` instead of the default `commit()` by setting `__persistence_method__` to `SQLAlchemyPersistenceMethod.FLUSH`. This example shows the factory setup with the persistence method override. ```python from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory, SQLAlchemyPersistenceMethod class Base(DeclarativeBase): ... class Author(Base): __tablename__ = "authors" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] class AuthorFactory(SQLAlchemyFactory[Author]): __set_relationships__ = True __persistence_method__ = SQLAlchemyPersistenceMethod.FLUSH ``` -------------------------------- ### Defining and using persistence handlers Source: https://polyfactory.litestar.dev/latest/usage/configuration.html Shows how to define sync and async persistence handlers using the SyncPersistenceProtocol and AsyncPersistenceProtocol, and how to attach them to a factory via __sync_persistence__ and __async_persistence__. Includes tests for create_sync, create_batch_sync, create_async, and create_batch_async. ```python from asyncio import sleep from dataclasses import dataclass from uuid import UUID from polyfactory import AsyncPersistenceProtocol, SyncPersistenceProtocol from polyfactory.factories import DataclassFactory @dataclass class Person: id: UUID name: str # we will use a dictionary to persist values for the example mock_db: dict[UUID, Person] = {} class SyncPersistenceHandler(SyncPersistenceProtocol[Person]): def save(self, data: Person) -> Person: # do stuff here to persist the value, such as use an ORM or ODM, cache in redis etc. # in our case we simply save it in the dictionary. mock_db[data.id] = data return data def save_many(self, data: list[Person]) -> list[Person]: # same as for save, here we should store the list in persistence. # in this case, we use the same dictionary. for person in data: mock_db[person.id] = person return data class AsyncPersistenceHandler(AsyncPersistenceProtocol[Person]): async def save(self, data: Person) -> Person: # do stuff here to persist the value using an async method, such as an async ORM or ODM. # in our case we simply save it in the dictionary and add a minimal sleep to mock async. mock_db[data.id] = data await sleep(0.0001) return data async def save_many(self, data: list[Person]) -> list[Person]: # same as for the async save, here we should store the list in persistence using async logic. # we again store in dict, and mock async using sleep. for person in data: mock_db[person.id] = person await sleep(0.0001) return data class PersonFactory(DataclassFactory[Person]): __sync_persistence__ = SyncPersistenceHandler __async_persistence__ = AsyncPersistenceHandler def test_sync_persistence_build() -> None: person_instance = PersonFactory.create_sync() assert mock_db[person_instance.id] is person_instance def test_sync_persistence_batch() -> None: person_batch = PersonFactory.create_batch_sync(10) for person_instance in person_batch: assert mock_db[person_instance.id] is person_instance async def test_async_persistence_build() -> None: person_instance = await PersonFactory.create_async() assert mock_db[person_instance.id] is person_instance async def test_async_persistence_batch() -> None: person_batch = await PersonFactory.create_batch_async(10) for person_instance in person_batch: assert mock_db[person_instance.id] is person_instance ``` -------------------------------- ### Use Examples Values with msgspec MsgspecFactory Source: https://polyfactory.litestar.dev/latest/usage/configuration.html Set `__use_examples__ = True` to use examples from `Annotated` metadata with an `examples` list attribute, such as msgspec's `Meta(examples=...)`. Custom markers with an `examples` list attribute also work. Works with every factory, including nested types. ```python from typing import Annotated from msgspec import Meta, Struct from polyfactory.factories.msgspec_factory import MsgspecFactory _SUPPORTED_CURRENCIES = ["USD", "EUR", "INR"] class Payment(Struct): amount: int currency: Annotated[str, Meta(examples=_SUPPORTED_CURRENCIES)] class PaymentFactory(MsgspecFactory[Payment]): __use_examples__ = True def test_use_examples() -> None: instance = PaymentFactory.build() assert instance.currency in _SUPPORTED_CURRENCIES ``` -------------------------------- ### Use.__init__ Source: https://polyfactory.litestar.dev/latest/_modules/polyfactory/fields.html Wraps a callable to be invoked when building a factory attribute. Accepts the callable and its arguments. ```APIDOC ## Use.__init__ ### Description Wraps a callable to be invoked when building a factory attribute. Accepts the callable and its arguments. ### Method Constructor ### Signature `def __init__(self, fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> None` ### Parameters - **fn** (Callable[P, T]) - Required - A callable to wrap. - **args** (P.args) - Optional - Any args to pass to the callable. - **kwargs** (P.kwargs) - Optional - Any kwargs to pass to the callable. ### Returns None ``` -------------------------------- ### Prepare initial variables and build context Source: https://polyfactory.litestar.dev/latest/_modules/polyfactory/factories/base.html Pops '_build_context' from kwargs, adds the model to seen_models, and returns a tuple of result dict, post-generated dict, and build context. ```python _build_context = cls._get_build_context(kwargs.pop("_build_context", None)) _build_context["seen_models"].add(cls.__model__) result: dict[str, Any] = {**kwargs} generate_post: dict[str, PostGenerated] = {} return result, generate_post, _build_context ``` -------------------------------- ### SQLASyncPersistence.__init__ Source: https://polyfactory.litestar.dev/latest/reference/factories/sqlalchemy_factory.html Initializes a synchronous persistence handler for SQLAFactory with a session, persistence method, and optional cleanup callback. ```APIDOC ## SQLASyncPersistence.__init__ ### Description Initializes a synchronous persistence handler for SQLAFactory. ### Method Constructor ### Signature __init__(session: Session, persistence_method: SQLAlchemyPersistenceMethod = SQLAlchemyPersistenceMethod.COMMIT, cleanup_callback: Callable[[], None] | None = None) -> None ### Parameters - **session** (Session) - Required - The SQLAlchemy session to use for persistence. - **persistence_method** (SQLAlchemyPersistenceMethod) - Optional - The persistence method to use (default: COMMIT). - **cleanup_callback** (Callable[[], None] | None) - Optional - A callback to invoke after persistence operations. ### Returns None ``` -------------------------------- ### Imperative factory creation with create_factory Source: https://polyfactory.litestar.dev/latest/usage/declaring_factories.html Demonstrates creating a factory imperatively by calling create_factory(model=Pet) on DataclassFactory. The test builds a Pet instance and asserts its type. ```python from dataclasses import dataclass from enum import Enum from polyfactory.factories import DataclassFactory class Species(str, Enum): CAT = "Cat" DOG = "Dog" @dataclass class Pet: name: str species: Species sound: str def test_imperative_factory_creation() -> None: pet_factory = DataclassFactory.create_factory(model=Pet) pet_instance = pet_factory.build() assert isinstance(pet_instance, Pet) ``` -------------------------------- ### assert_never function implementation and docstring example Source: https://polyfactory.litestar.dev/latest/_modules/typing.html Implementation of assert_never with a docstring example showing a match statement that uses assert_never in the default case. ```python def int_or_str(arg: int | str) -> None: match arg: case int(): print("It's an int") case str(): print("It's a str") case _: assert_never(arg) ``` ```python _ASSERT_NEVER_REPR_MAX_LENGTH = 100 def assert_never(arg: Never, /) -> Never: """Statically assert that a line of code is unreachable. Example:: def int_or_str(arg: int | str) -> None: match arg: case int(): print("It's an int") case str(): print("It's a str") case _: assert_never(arg) If a type checker finds that a call to assert_never() is reachable, it will emit an error. At runtime, this throws an exception when called. """ value = repr(arg) if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH: value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...' raise AssertionError(f"Expected code to be unreachable, but got: {value}") ``` -------------------------------- ### TypeGuard usage example Source: https://polyfactory.litestar.dev/latest/_modules/typing.html Example of using TypeGuard as a return type for a type predicate function. The function returns True if all objects in the list are strings, narrowing the argument type to list[str]. ```python def is_str_list(val: list[object]) -> TypeGuard[list[str]]: '''Determines whether all objects in the list are strings''' return all(isinstance(x, str) for x in val) def func1(val: list[object]): if is_str_list(val): # Type of ``val`` is narrowed to ``list[str]``. print(" ".join(val)) else: # Type of ``val`` remains as ``list[object]``. print("Not a list of strings!") ``` -------------------------------- ### Map provider method to factories and weights Source: https://polyfactory.litestar.dev/latest/_modules/faker/proxy.html Creates a 2-tuple of compatible factories and distribution weights for a given provider method, caching the result. Raises AttributeError if no factory supports the method. ```python def _map_provider_method(self, method_name: str) -> tuple[list[Factory], list[float] | None]: """ Creates a 2-tuple of factories and weights for the given provider method name The first element of the tuple contains a list of compatible factories. The second element of the tuple contains a list of distribution weights. :param method_name: Name of provider method :return: 2-tuple (factories, weights) """ # Return cached mapping if it exists for given method attr = f"_cached_{method_name}_mapping" if hasattr(self, attr): return getattr(self, attr) # Create mapping if it does not exist if self._weights: value = [ (factory, weight) for factory, weight in zip(self.factories, self._weights) if hasattr(factory, method_name) ] factories, weights = zip(*value) mapping = list(factories), list(weights) else: value = [factory for factory in self.factories if hasattr(factory, method_name)] # type: ignore mapping = value, None # type: ignore # Then cache and return results setattr(self, attr, mapping) return mapping ``` -------------------------------- ### TypeIs usage example Source: https://polyfactory.litestar.dev/latest/_modules/typing.html Example of using TypeIs as a return type for a type predicate function. The function checks if an object is an instance of Parent, narrowing the argument type to the intersection with Parent when True, and excluding Parent when False. ```python from typing import assert_type, final, TypeIs class Parent: pass class Child(Parent): pass @final class Unrelated: pass def is_parent(val: object) -> TypeIs[Parent]: return isinstance(val, Parent) def run(arg: Child | Unrelated): if is_parent(arg): # Type of ``arg`` is narrowed to the intersection # of ``Parent`` and ``Child``, which is equivalent to # ``Child``. assert_type(arg, Child) else: # Type of ``arg`` is narrowed to exclude ``Parent``, # so only ``Unrelated`` is left. assert_type(arg, Unrelated) ``` -------------------------------- ### Annotated special form with usage examples Source: https://polyfactory.litestar.dev/latest/_modules/typing.html Defines the Annotated special form that adds context-specific metadata to a type. Includes examples showing metadata access, flattening, instantiation, generic aliases, and invalid usage with unpacked TypeVarTuple. ```python @_TypedCacheSpecialForm @_tp_cache(typed=True) def Annotated(self, *params): """Add context-specific metadata to a type. Example: Annotated[int, runtime_check.Unsigned] indicates to the hypothetical runtime_check module that this type is an unsigned int. Every other consumer of this type can ignore this metadata and treat this type as int. The first argument to Annotated must be a valid type. Details: - It's an error to call `Annotated` with less than two arguments. - Access the metadata via the ``__metadata__`` attribute:: assert Annotated[int, '$'].__metadata__ == ('$',) - Nested Annotated types are flattened:: assert Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] - Instantiating an annotated type is equivalent to instantiating the underlying type:: assert Annotated[C, Ann1](5) == C(5) - Annotated can be used as a generic type alias:: type Optimized[T] = Annotated[T, runtime.Optimize()] # type checker will treat Optimized[int] # as equivalent to Annotated[int, runtime.Optimize()] type OptimizedList[T] = Annotated[list[T], runtime.Optimize()] # type checker will treat OptimizedList[int] # as equivalent to Annotated[list[int], runtime.Optimize()] - Annotated cannot be used with an unpacked TypeVarTuple:: type Variadic[*Ts] = Annotated[*Ts, Ann1] # NOT valid This would be equivalent to:: Annotated[T1, T2, T3, ..., Ann1] """ ``` -------------------------------- ### PydanticFactory __config_keys__ and _init_model Source: https://polyfactory.litestar.dev/latest/_modules/polyfactory/factories/pydantic_factory.html Defines the configuration keys tuple and initializes the model, handling pydantic v1 and v2 specifics, including __by_name__ validation and forward refs resolution. ```python __config_keys__ = ( *BaseFactory.__config_keys__, "__by_name__", ) @classmethod def _init_model(cls) -> None: super()._init_model() model = getattr(cls, "__model__", None) if model is None: return if cls.__by_name__ and _is_pydantic_v2_model(model) and not _PYDANTIC_HAS_BY_NAME: msg = ( f"__by_name__ requires pydantic>=2.11, but pydantic {VERSION} is installed. " "Upgrade pydantic, or set `populate_by_name=True` on the model so that it also accepts " "its field names, or remove `__by_name__` from the factory." ) raise ConfigurationException(msg) if _is_pydantic_v1_model(model) and hasattr(cls.__model__, "update_forward_refs"): with suppress(NameError): # pragma: no cover cls.__model__.update_forward_refs(**cls.__forward_ref_resolution_type_mapping__) if _is_pydantic_v2_model(model): model.model_rebuild() ``` -------------------------------- ### batch method implementation Source: https://polyfactory.litestar.dev/latest/_modules/polyfactory/factories/base.html Builds a batch of size n of the factory's Meta.model. ```python return [cls.build(**kwargs) for _ in range(size)] ``` -------------------------------- ### PydanticFieldMeta.get_constraints_metadata Source: https://polyfactory.litestar.dev/latest/reference/factories/pydantic_factory.html Gets the metadata of constraints from a given annotation. ```APIDOC ## PydanticFieldMeta.get_constraints_metadata ### Description Gets the metadata of constraints from a given annotation. ### Method Classmethod ### Parameters #### Parameters - **annotation** (Any) - Required - A type annotation. ### Returns A list of metadata in the annotation. ``` -------------------------------- ### FieldMeta.get_constraints_metadata Source: https://polyfactory.litestar.dev/latest/reference/field_meta.html Get the metadatas of the constraints from the given annotation. ```APIDOC ## FieldMeta.get_constraints_metadata ### Description Get the metadatas of the constraints from the given annotation. ### Method Classmethod ### Signature `get_constraints_metadata(annotation: Any) -> Sequence[Any]` ### Parameters - **annotation** (Any) - Required - A type annotation. ### Returns Sequence[Any] - A list of the metadata in the annotation. ``` -------------------------------- ### BaseFactory.build Source: https://polyfactory.litestar.dev/latest/_modules/polyfactory/factories/base.html Builds an instance of the factory's __model__ using the provided keyword arguments. ```APIDOC ## build ### Description Build an instance of the factory's __model__. ### Method classmethod ### Signature `build(cls, *_: Any, **kwargs: Any) -> T` ### Parameters - **kwargs** (Any) - Optional - Any kwargs. If field names are set in kwargs, their values will be used. ### Returns - **T** - An instance of type T. ``` -------------------------------- ### coverage method implementation Source: https://polyfactory.litestar.dev/latest/_modules/polyfactory/factories/base.html Builds a batch of the factory's Meta.model with full coverage of the sub-types of the model. ```python for data in cls.process_kwargs_coverage(**kwargs): instance = cls.__model__(**data) yield instance ``` -------------------------------- ### Declare a SQLAlchemyFactory for a SQLAlchemy model Source: https://polyfactory.litestar.dev/latest/usage/library_factories/sqlalchemy_factory.html Shows how to declare a factory for a SQLAlchemy model using SQLAlchemyFactory. The example defines a Base class, an Author model, and an AuthorFactory, then builds an Author instance and asserts its type. Requires SQLAlchemy 2 to run, though the factory supports both 1.4 and 2. ```python from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory class Base(DeclarativeBase): ... class Author(Base): __tablename__ = "authors" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] class AuthorFactory(SQLAlchemyFactory[Author]): ... def test_sqla_factory() -> None: author = AuthorFactory.build() assert isinstance(author, Author) ``` -------------------------------- ### get_origin Source: https://polyfactory.litestar.dev/latest/_modules/typing.html Get the unsubscripted version of a type. This is useful for introspection of type hints. ```APIDOC ## get_origin ### Description Get the unsubscripted version of a type. This is useful for introspection of type hints. ### Function Signature `get_origin(tp)` ### Parameters - **tp** (type) - Required - The type to inspect. ### Returns - The unsubscripted version of the type, or None if not applicable. ### Examples ```python >>> P = ParamSpec('P') >>> assert get_origin(Literal[42]) is Literal >>> assert get_origin(int) is None >>> assert get_origin(ClassVar[int]) is ClassVar >>> assert get_origin(Generic) is Generic >>> assert get_origin(Generic[T]) is Generic >>> assert get_origin(Union[T, int]) is Union >>> assert get_origin(List[Tuple[T, T]][int]) is list >>> assert get_origin(P.args) is P ``` ``` -------------------------------- ### Dynamic factory generation example Source: https://polyfactory.litestar.dev/latest/usage/configuration.html Shows how Polyfactory dynamically generates a PetFactory when PersonFactory.build() is called. The generated factory is cached and reused. The test asserts that the generated pets list is non-empty and contains Pet instances. ```python from dataclasses import dataclass from datetime import date, datetime from enum import Enum from typing import Any, Union from uuid import UUID from polyfactory.factories import DataclassFactory class Species(str, Enum): CAT = "Cat" DOG = "Dog" @dataclass class Pet: name: str species: Species sound: str @dataclass class Person: id: UUID name: str hobbies: list[str] age: Union[float, int] birthday: Union[datetime, date] pets: list[Pet] assets: list[dict[str, dict[str, Any]]] class PersonFactory(DataclassFactory[Person]): ... def test_dynamic_factory_generation() -> None: person_instance = PersonFactory.build() assert len(person_instance.pets) > 0 assert isinstance(person_instance.pets[0], Pet) ``` -------------------------------- ### Get Origin Function Definition Source: https://polyfactory.litestar.dev/latest/_modules/typing.html Defines the entry point for retrieving the unsubscripted version of a type. ```python def get_origin(tp): """Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar, Annotated, and others. Return None for unsupported types. Examples:: ``` -------------------------------- ### create Source: https://polyfactory.litestar.dev/latest/_modules/polyfactory/factories/base.html Builds and persists a single model instance synchronously. ```APIDOC ## create ### Description Builds and persists a single model instance synchronously. ### Method create ### Parameters - **kwargs** (Any) - Optional - Any kwargs. If field_meta names are set in kwargs, their values will be used. ### Returns An instance of type T. ``` -------------------------------- ### SQLAASyncPersistence.__init__ Source: https://polyfactory.litestar.dev/latest/reference/factories/sqlalchemy_factory.html Initializes an asynchronous persistence handler for SQLAFactory. ```APIDOC ## SQLAASyncPersistence.__init__ ### Description Initializes an async persistence handler for SQLAFactory. ### Method Constructor ### Signature __init__(session: AsyncSession, persistence_method: SQLAlchemyPersistenceMethod = SQLAlchemyPersistenceMethod.COMMIT, cleanup_callback: Callable[[], Awaitable[None]] | None = None) -> None ### Parameters - **session** (AsyncSession) - Required - The SQLAlchemy async session to use for persistence. - **persistence_method** (SQLAlchemyPersistenceMethod) - Optional - The persistence method to use (default: COMMIT). - **cleanup_callback** (Callable[[], Awaitable[None]] | None) - Optional - An async callback to invoke after persistence operations. ### Returns None ```