Skip to content

2. Action Sequence

SequenceActionable — eager collection (list/tuple). Class and function styles.

Source

"""SequenceActionable — eager collection (list/tuple). Class and function styles."""

import asyncio
from collections.abc import Sequence

from fastsprout.core.action import SequenceActionable
from fastsprout.core.fields import Field
from fastsprout.core.schema import BaseSchema


class GreetBatchIn(BaseSchema):
    name: Field[str]
    times: Field[int]


class GreetOut(BaseSchema):
    message: Field[str]


class GreetBatch(SequenceActionable[GreetBatchIn, GreetOut]):
    async def __call__(self, payload: GreetBatchIn, /) -> Sequence[GreetOut]:
        return [
            GreetOut(message=f"hello, {payload.name} #{i}")
            for i in range(payload.times)
        ]


async def greet_batch(payload: GreetBatchIn, /) -> Sequence[GreetOut]:
    return [
        GreetOut(message=f"hello, {payload.name} #{i}")
        for i in range(payload.times)
    ]


async def main() -> None:
    payload = GreetBatchIn(name="world", times=3)

    print([g.message for g in await GreetBatch()(payload)])
    print([g.message for g in await greet_batch(payload)])


if __name__ == "__main__":
    asyncio.run(main())

Result

['hello, world #0', 'hello, world #1', 'hello, world #2']
['hello, world #0', 'hello, world #1', 'hello, world #2']