Skip to content

prefect.main

Flow

Bases: Generic[P, R]

A Prefect workflow definition.

Note

We recommend using the @flow decorator for most use-cases.

Wraps a function with an entrypoint to the Prefect engine. To preserve the input and output types, we use the generic type variables P and R for "Parameters" and "Returns" respectively.

Parameters:

Name Type Description Default
fn Callable[P, R]

The function defining the workflow.

required
name Optional[str]

An optional name for the flow; if not provided, the name will be inferred from the given function.

None
version Optional[str]

An optional version string for the flow; if not provided, we will attempt to create a version string as a hash of the file containing the wrapped function; if the file cannot be located, the version will be null.

None
flow_run_name Optional[Union[Callable[[], str], str]]

An optional name to distinguish runs of this flow; this name can be provided as a string template with the flow's parameters as variables, or a function that returns a string.

None
task_runner Union[Type[TaskRunner], TaskRunner, None]

An optional task runner to use for task execution within the flow; if not provided, a ThreadPoolTaskRunner will be used.

None
description Optional[str]

An optional string description for the flow; if not provided, the description will be pulled from the docstring for the decorated function.

None
timeout_seconds Union[int, float, None]

An optional number of seconds indicating a maximum runtime for the flow. If the flow exceeds this runtime, it will be marked as failed. Flow execution may continue until the next task is called.

None
validate_parameters bool

By default, parameters passed to flows are validated by Pydantic. This will check that input values conform to the annotated types on the function. Where possible, values will be coerced into the correct type; for example, if a parameter is defined as x: int and "5" is passed, it will be resolved to 5. If set to False, no validation will be performed on flow parameters.

True
retries Optional[int]

An optional number of times to retry on flow run failure.

None
retry_delay_seconds Optional[Union[int, float]]

An optional number of seconds to wait before retrying the flow after failure. This is only applicable if retries is nonzero.

None
persist_result Optional[bool]

An optional toggle indicating whether the result of this flow should be persisted to result storage. Defaults to None, which indicates that Prefect should choose whether the result should be persisted depending on the features being used.

None
result_storage Optional[ResultStorage]

An optional block to use to persist the result of this flow. This value will be used as the default for any tasks in this flow. If not provided, the local file system will be used unless called as a subflow, at which point the default will be loaded from the parent flow.

None
result_serializer Optional[ResultSerializer]

An optional serializer to use to serialize the result of this flow for persistence. This value will be used as the default for any tasks in this flow. If not provided, the value of PREFECT_RESULTS_DEFAULT_SERIALIZER will be used unless called as a subflow, at which point the default will be loaded from the parent flow.

None
on_failure Optional[List[Callable[[Flow, FlowRun, State], None]]]

An optional list of callables to run when the flow enters a failed state.

None
on_completion Optional[List[Callable[[Flow, FlowRun, State], None]]]

An optional list of callables to run when the flow enters a completed state.

None
on_cancellation Optional[List[Callable[[Flow, FlowRun, State], None]]]

An optional list of callables to run when the flow enters a cancelling state.

None
on_crashed Optional[List[Callable[[Flow, FlowRun, State], None]]]

An optional list of callables to run when the flow enters a crashed state.

None
on_running Optional[List[Callable[[Flow, FlowRun, State], None]]]

An optional list of callables to run when the flow enters a running state.

None
Source code in src/prefect/flows.py
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
class Flow(Generic[P, R]):
    """
    A Prefect workflow definition.

    !!! note
        We recommend using the [`@flow` decorator][prefect.flows.flow] for most use-cases.

    Wraps a function with an entrypoint to the Prefect engine. To preserve the input
    and output types, we use the generic type variables `P` and `R` for "Parameters" and
    "Returns" respectively.

    Args:
        fn: The function defining the workflow.
        name: An optional name for the flow; if not provided, the name will be inferred
            from the given function.
        version: An optional version string for the flow; if not provided, we will
            attempt to create a version string as a hash of the file containing the
            wrapped function; if the file cannot be located, the version will be null.
        flow_run_name: An optional name to distinguish runs of this flow; this name can
            be provided as a string template with the flow's parameters as variables,
            or a function that returns a string.
        task_runner: An optional task runner to use for task execution within the flow;
            if not provided, a `ThreadPoolTaskRunner` will be used.
        description: An optional string description for the flow; if not provided, the
            description will be pulled from the docstring for the decorated function.
        timeout_seconds: An optional number of seconds indicating a maximum runtime for
            the flow. If the flow exceeds this runtime, it will be marked as failed.
            Flow execution may continue until the next task is called.
        validate_parameters: By default, parameters passed to flows are validated by
            Pydantic. This will check that input values conform to the annotated types
            on the function. Where possible, values will be coerced into the correct
            type; for example, if a parameter is defined as `x: int` and "5" is passed,
            it will be resolved to `5`. If set to `False`, no validation will be
            performed on flow parameters.
        retries: An optional number of times to retry on flow run failure.
        retry_delay_seconds: An optional number of seconds to wait before retrying the
            flow after failure. This is only applicable if `retries` is nonzero.
        persist_result: An optional toggle indicating whether the result of this flow
            should be persisted to result storage. Defaults to `None`, which indicates
            that Prefect should choose whether the result should be persisted depending on
            the features being used.
        result_storage: An optional block to use to persist the result of this flow.
            This value will be used as the default for any tasks in this flow.
            If not provided, the local file system will be used unless called as
            a subflow, at which point the default will be loaded from the parent flow.
        result_serializer: An optional serializer to use to serialize the result of this
            flow for persistence. This value will be used as the default for any tasks
            in this flow. If not provided, the value of `PREFECT_RESULTS_DEFAULT_SERIALIZER`
            will be used unless called as a subflow, at which point the default will be
            loaded from the parent flow.
        on_failure: An optional list of callables to run when the flow enters a failed state.
        on_completion: An optional list of callables to run when the flow enters a completed state.
        on_cancellation: An optional list of callables to run when the flow enters a cancelling state.
        on_crashed: An optional list of callables to run when the flow enters a crashed state.
        on_running: An optional list of callables to run when the flow enters a running state.
    """

    # NOTE: These parameters (types, defaults, and docstrings) should be duplicated
    #       exactly in the @flow decorator
    def __init__(
        self,
        fn: Callable[P, R],
        name: Optional[str] = None,
        version: Optional[str] = None,
        flow_run_name: Optional[Union[Callable[[], str], str]] = None,
        retries: Optional[int] = None,
        retry_delay_seconds: Optional[Union[int, float]] = None,
        task_runner: Union[Type[TaskRunner], TaskRunner, None] = None,
        description: Optional[str] = None,
        timeout_seconds: Union[int, float, None] = None,
        validate_parameters: bool = True,
        persist_result: Optional[bool] = None,
        result_storage: Optional[ResultStorage] = None,
        result_serializer: Optional[ResultSerializer] = None,
        cache_result_in_memory: bool = True,
        log_prints: Optional[bool] = None,
        on_completion: Optional[
            List[Callable[[FlowSchema, FlowRun, State], None]]
        ] = None,
        on_failure: Optional[List[Callable[[FlowSchema, FlowRun, State], None]]] = None,
        on_cancellation: Optional[
            List[Callable[[FlowSchema, FlowRun, State], None]]
        ] = None,
        on_crashed: Optional[List[Callable[[FlowSchema, FlowRun, State], None]]] = None,
        on_running: Optional[List[Callable[[FlowSchema, FlowRun, State], None]]] = None,
    ):
        if name is not None and not isinstance(name, str):
            raise TypeError(
                "Expected string for flow parameter 'name'; got {} instead. {}".format(
                    type(name).__name__,
                    (
                        "Perhaps you meant to call it? e.g."
                        " '@flow(name=get_flow_run_name())'"
                        if callable(name)
                        else ""
                    ),
                )
            )

        # Validate if hook passed is list and contains callables
        hook_categories = [
            on_completion,
            on_failure,
            on_cancellation,
            on_crashed,
            on_running,
        ]
        hook_names = [
            "on_completion",
            "on_failure",
            "on_cancellation",
            "on_crashed",
            "on_running",
        ]
        for hooks, hook_name in zip(hook_categories, hook_names):
            if hooks is not None:
                try:
                    hooks = list(hooks)
                except TypeError:
                    raise TypeError(
                        f"Expected iterable for '{hook_name}'; got"
                        f" {type(hooks).__name__} instead. Please provide a list of"
                        f" hooks to '{hook_name}':\n\n"
                        f"@flow({hook_name}=[hook1, hook2])\ndef"
                        " my_flow():\n\tpass"
                    )

                for hook in hooks:
                    if not callable(hook):
                        raise TypeError(
                            f"Expected callables in '{hook_name}'; got"
                            f" {type(hook).__name__} instead. Please provide a list of"
                            f" hooks to '{hook_name}':\n\n"
                            f"@flow({hook_name}=[hook1, hook2])\ndef"
                            " my_flow():\n\tpass"
                        )

        if not callable(fn):
            raise TypeError("'fn' must be callable")

        # Validate name if given
        if name:
            _raise_on_name_with_banned_characters(name)

        self.name = name or fn.__name__.replace("_", "-")

        if flow_run_name is not None:
            if not isinstance(flow_run_name, str) and not callable(flow_run_name):
                raise TypeError(
                    "Expected string or callable for 'flow_run_name'; got"
                    f" {type(flow_run_name).__name__} instead."
                )
        self.flow_run_name = flow_run_name

        default_task_runner = ThreadPoolTaskRunner()
        task_runner = task_runner or default_task_runner
        self.task_runner = (
            task_runner() if isinstance(task_runner, type) else task_runner
        )

        self.log_prints = log_prints

        self.description = description or inspect.getdoc(fn)
        update_wrapper(self, fn)
        self.fn = fn

        # the flow is considered async if its function is async or an async
        # generator
        self.isasync = inspect.iscoroutinefunction(
            self.fn
        ) or inspect.isasyncgenfunction(self.fn)

        # the flow is considered a generator if its function is a generator or
        # an async generator
        self.isgenerator = inspect.isgeneratorfunction(
            self.fn
        ) or inspect.isasyncgenfunction(self.fn)

        raise_for_reserved_arguments(self.fn, ["return_state", "wait_for"])

        # Version defaults to a hash of the function's file
        flow_file = inspect.getsourcefile(self.fn)
        if not version:
            try:
                version = file_hash(flow_file)
            except (FileNotFoundError, TypeError, OSError):
                pass  # `getsourcefile` can return null values and "<stdin>" for objects in repls
        self.version = version

        self.timeout_seconds = float(timeout_seconds) if timeout_seconds else None

        # FlowRunPolicy settings
        # TODO: We can instantiate a `FlowRunPolicy` and add Pydantic bound checks to
        #       validate that the user passes positive numbers here
        self.retries = (
            retries if retries is not None else PREFECT_FLOW_DEFAULT_RETRIES.value()
        )

        self.retry_delay_seconds = (
            retry_delay_seconds
            if retry_delay_seconds is not None
            else PREFECT_FLOW_DEFAULT_RETRY_DELAY_SECONDS.value()
        )

        self.parameters = parameter_schema(self.fn)
        self.should_validate_parameters = validate_parameters

        if self.should_validate_parameters:
            # Try to create the validated function now so that incompatibility can be
            # raised at declaration time rather than at runtime
            # We cannot, however, store the validated function on the flow because it
            # is not picklable in some environments
            try:
                ValidatedFunction(self.fn, config={"arbitrary_types_allowed": True})
            except ConfigError as exc:
                raise ValueError(
                    "Flow function is not compatible with `validate_parameters`. "
                    "Disable validation or change the argument names."
                ) from exc

        self.persist_result = persist_result
        self.result_storage = result_storage
        self.result_serializer = result_serializer
        self.cache_result_in_memory = cache_result_in_memory
        self.on_completion_hooks = on_completion or []
        self.on_failure_hooks = on_failure or []
        self.on_cancellation_hooks = on_cancellation or []
        self.on_crashed_hooks = on_crashed or []
        self.on_running_hooks = on_running or []

        # Used for flows loaded from remote storage
        self._storage: Optional[RunnerStorage] = None
        self._entrypoint: Optional[str] = None

        module = fn.__module__
        if module in ("__main__", "__prefect_loader__"):
            module_name = inspect.getfile(fn)
            module = module_name if module_name != "__main__" else module

        self._entrypoint = f"{module}:{fn.__name__}"

    @property
    def ismethod(self) -> bool:
        return hasattr(self.fn, "__prefect_self__")

    def __get__(self, instance, owner):
        """
        Implement the descriptor protocol so that the flow can be used as an instance method.
        When an instance method is loaded, this method is called with the "self" instance as
        an argument. We return a copy of the flow with that instance bound to the flow's function.
        """

        # if no instance is provided, it's being accessed on the class
        if instance is None:
            return self

        # if the flow is being accessed on an instance, bind the instance to the __prefect_self__ attribute
        # of the flow's function. This will allow it to be automatically added to the flow's parameters
        else:
            bound_flow = copy(self)
            bound_flow.fn.__prefect_self__ = instance
            return bound_flow

    def with_options(
        self,
        *,
        name: Optional[str] = None,
        version: Optional[str] = None,
        retries: Optional[int] = None,
        retry_delay_seconds: Optional[Union[int, float]] = None,
        description: Optional[str] = None,
        flow_run_name: Optional[Union[Callable[[], str], str]] = None,
        task_runner: Union[Type[TaskRunner], TaskRunner, None] = None,
        timeout_seconds: Union[int, float, None] = None,
        validate_parameters: Optional[bool] = None,
        persist_result: Optional[bool] = NotSet,  # type: ignore
        result_storage: Optional[ResultStorage] = NotSet,  # type: ignore
        result_serializer: Optional[ResultSerializer] = NotSet,  # type: ignore
        cache_result_in_memory: Optional[bool] = None,
        log_prints: Optional[bool] = NotSet,  # type: ignore
        on_completion: Optional[
            List[Callable[[FlowSchema, FlowRun, State], None]]
        ] = None,
        on_failure: Optional[List[Callable[[FlowSchema, FlowRun, State], None]]] = None,
        on_cancellation: Optional[
            List[Callable[[FlowSchema, FlowRun, State], None]]
        ] = None,
        on_crashed: Optional[List[Callable[[FlowSchema, FlowRun, State], None]]] = None,
        on_running: Optional[List[Callable[[FlowSchema, FlowRun, State], None]]] = None,
    ) -> Self:
        """
        Create a new flow from the current object, updating provided options.

        Args:
            name: A new name for the flow.
            version: A new version for the flow.
            description: A new description for the flow.
            flow_run_name: An optional name to distinguish runs of this flow; this name
                can be provided as a string template with the flow's parameters as variables,
                or a function that returns a string.
            task_runner: A new task runner for the flow.
            timeout_seconds: A new number of seconds to fail the flow after if still
                running.
            validate_parameters: A new value indicating if flow calls should validate
                given parameters.
            retries: A new number of times to retry on flow run failure.
            retry_delay_seconds: A new number of seconds to wait before retrying the
                flow after failure. This is only applicable if `retries` is nonzero.
            persist_result: A new option for enabling or disabling result persistence.
            result_storage: A new storage type to use for results.
            result_serializer: A new serializer to use for results.
            cache_result_in_memory: A new value indicating if the flow's result should
                be cached in memory.
            on_failure: A new list of callables to run when the flow enters a failed state.
            on_completion: A new list of callables to run when the flow enters a completed state.
            on_cancellation: A new list of callables to run when the flow enters a cancelling state.
            on_crashed: A new list of callables to run when the flow enters a crashed state.
            on_running: A new list of callables to run when the flow enters a running state.

        Returns:
            A new `Flow` instance.

        Examples:

            Create a new flow from an existing flow and update the name:

            >>> @flow(name="My flow")
            >>> def my_flow():
            >>>     return 1
            >>>
            >>> new_flow = my_flow.with_options(name="My new flow")

            Create a new flow from an existing flow, update the task runner, and call
            it without an intermediate variable:

            >>> from prefect.task_runners import ThreadPoolTaskRunner
            >>>
            >>> @flow
            >>> def my_flow(x, y):
            >>>     return x + y
            >>>
            >>> state = my_flow.with_options(task_runner=ThreadPoolTaskRunner)(1, 3)
            >>> assert state.result() == 4
        """
        new_flow = Flow(
            fn=self.fn,
            name=name or self.name,
            description=description or self.description,
            flow_run_name=flow_run_name or self.flow_run_name,
            version=version or self.version,
            task_runner=task_runner or self.task_runner,
            retries=retries if retries is not None else self.retries,
            retry_delay_seconds=(
                retry_delay_seconds
                if retry_delay_seconds is not None
                else self.retry_delay_seconds
            ),
            timeout_seconds=(
                timeout_seconds if timeout_seconds is not None else self.timeout_seconds
            ),
            validate_parameters=(
                validate_parameters
                if validate_parameters is not None
                else self.should_validate_parameters
            ),
            persist_result=(
                persist_result if persist_result is not NotSet else self.persist_result
            ),
            result_storage=(
                result_storage if result_storage is not NotSet else self.result_storage
            ),
            result_serializer=(
                result_serializer
                if result_serializer is not NotSet
                else self.result_serializer
            ),
            cache_result_in_memory=(
                cache_result_in_memory
                if cache_result_in_memory is not None
                else self.cache_result_in_memory
            ),
            log_prints=log_prints if log_prints is not NotSet else self.log_prints,
            on_completion=on_completion or self.on_completion_hooks,
            on_failure=on_failure or self.on_failure_hooks,
            on_cancellation=on_cancellation or self.on_cancellation_hooks,
            on_crashed=on_crashed or self.on_crashed_hooks,
            on_running=on_running or self.on_running_hooks,
        )
        new_flow._storage = self._storage
        new_flow._entrypoint = self._entrypoint
        return new_flow

    def validate_parameters(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
        """
        Validate parameters for compatibility with the flow by attempting to cast the inputs to the
        associated types specified by the function's type annotations.

        Returns:
            A new dict of parameters that have been cast to the appropriate types

        Raises:
            ParameterTypeError: if the provided parameters are not valid
        """
        args, kwargs = parameters_to_args_kwargs(self.fn, parameters)

        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore", category=pydantic.warnings.PydanticDeprecatedSince20
            )
            has_v1_models = any(isinstance(o, V1BaseModel) for o in args) or any(
                isinstance(o, V1BaseModel) for o in kwargs.values()
            )

        has_v2_types = any(is_v2_type(o) for o in args) or any(
            is_v2_type(o) for o in kwargs.values()
        )

        if has_v1_models and has_v2_types:
            raise ParameterTypeError(
                "Cannot mix Pydantic v1 and v2 types as arguments to a flow."
            )

        if has_v1_models:
            validated_fn = V1ValidatedFunction(
                self.fn, config={"arbitrary_types_allowed": True}
            )
        else:
            validated_fn = V2ValidatedFunction(
                self.fn, config=pydantic.ConfigDict(arbitrary_types_allowed=True)
            )

        try:
            with warnings.catch_warnings():
                warnings.filterwarnings(
                    "ignore", category=pydantic.warnings.PydanticDeprecatedSince20
                )
                model = validated_fn.init_model_instance(*args, **kwargs)
        except pydantic.ValidationError as exc:
            # We capture the pydantic exception and raise our own because the pydantic
            # exception is not picklable when using a cythonized pydantic installation
            logger.error(
                f"Parameter validation failed for flow {self.name!r}: {exc.errors()}"
                f"\nParameters: {parameters}"
            )
            raise ParameterTypeError.from_validation_error(exc) from None

        # Get the updated parameter dict with cast values from the model
        cast_parameters = {
            k: v
            for k, v in dict(model).items()
            if k in model.model_fields_set or model.model_fields[k].default_factory
        }
        return cast_parameters

    def serialize_parameters(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
        """
        Convert parameters to a serializable form.

        Uses FastAPI's `jsonable_encoder` to convert to JSON compatible objects without
        converting everything directly to a string. This maintains basic types like
        integers during API roundtrips.
        """
        serialized_parameters = {}
        for key, value in parameters.items():
            # do not serialize the bound self object
            if self.ismethod and value is self.fn.__prefect_self__:
                continue
            try:
                serialized_parameters[key] = jsonable_encoder(value)
            except (TypeError, ValueError):
                logger.debug(
                    f"Parameter {key!r} for flow {self.name!r} is of unserializable "
                    f"type {type(value).__name__!r} and will not be stored "
                    "in the backend."
                )
                serialized_parameters[key] = f"<{type(value).__name__}>"
        return serialized_parameters

    @sync_compatible
    @deprecated_parameter(
        "schedule",
        start_date="Mar 2024",
        when=lambda p: p is not None,
        help="Use `schedules` instead.",
    )
    @deprecated_parameter(
        "is_schedule_active",
        start_date="Mar 2024",
        when=lambda p: p is not None,
        help="Use `paused` instead.",
    )
    async def to_deployment(
        self,
        name: str,
        interval: Optional[
            Union[
                Iterable[Union[int, float, datetime.timedelta]],
                int,
                float,
                datetime.timedelta,
            ]
        ] = None,
        cron: Optional[Union[Iterable[str], str]] = None,
        rrule: Optional[Union[Iterable[str], str]] = None,
        paused: Optional[bool] = None,
        schedules: Optional[List["FlexibleScheduleList"]] = None,
        schedule: Optional[SCHEDULE_TYPES] = None,
        is_schedule_active: Optional[bool] = None,
        parameters: Optional[dict] = None,
        triggers: Optional[List[Union[DeploymentTriggerTypes, TriggerTypes]]] = None,
        description: Optional[str] = None,
        tags: Optional[List[str]] = None,
        version: Optional[str] = None,
        enforce_parameter_schema: bool = True,
        work_pool_name: Optional[str] = None,
        work_queue_name: Optional[str] = None,
        job_variables: Optional[Dict[str, Any]] = None,
        entrypoint_type: EntrypointType = EntrypointType.FILE_PATH,
    ) -> "RunnerDeployment":
        """
        Creates a runner deployment object for this flow.

        Args:
            name: The name to give the created deployment.
            interval: An interval on which to execute the new deployment. Accepts either a number
                or a timedelta object. If a number is given, it will be interpreted as seconds.
            cron: A cron schedule of when to execute runs of this deployment.
            rrule: An rrule schedule of when to execute runs of this deployment.
            paused: Whether or not to set this deployment as paused.
            schedules: A list of schedule objects defining when to execute runs of this deployment.
                Used to define multiple schedules or additional scheduling options such as `timezone`.
            schedule: A schedule object defining when to execute runs of this deployment.
            is_schedule_active: Whether or not to set the schedule for this deployment as active. If
                not provided when creating a deployment, the schedule will be set as active. If not
                provided when updating a deployment, the schedule's activation will not be changed.
            parameters: A dictionary of default parameter values to pass to runs of this deployment.
            triggers: A list of triggers that will kick off runs of this deployment.
            description: A description for the created deployment. Defaults to the flow's
                description if not provided.
            tags: A list of tags to associate with the created deployment for organizational
                purposes.
            version: A version for the created deployment. Defaults to the flow's version.
            enforce_parameter_schema: Whether or not the Prefect API should enforce the
                parameter schema for the created deployment.
            work_pool_name: The name of the work pool to use for this deployment.
            work_queue_name: The name of the work queue to use for this deployment's scheduled runs.
                If not provided the default work queue for the work pool will be used.
            job_variables: Settings used to override the values specified default base job template
                of the chosen work pool. Refer to the base job template of the chosen work pool for
            entrypoint_type: Type of entrypoint to use for the deployment. When using a module path
                entrypoint, ensure that the module will be importable in the execution environment.

        Examples:
            Prepare two deployments and serve them:

            ```python
            from prefect import flow, serve

            @flow
            def my_flow(name):
                print(f"hello {name}")

            @flow
            def my_other_flow(name):
                print(f"goodbye {name}")

            if __name__ == "__main__":
                hello_deploy = my_flow.to_deployment("hello", tags=["dev"])
                bye_deploy = my_other_flow.to_deployment("goodbye", tags=["dev"])
                serve(hello_deploy, bye_deploy)
            ```
        """
        from prefect.deployments.runner import RunnerDeployment

        if not name.endswith(".py"):
            _raise_on_name_with_banned_characters(name)

        if self._storage and self._entrypoint:
            return await RunnerDeployment.from_storage(
                storage=self._storage,
                entrypoint=self._entrypoint,
                name=name,
                interval=interval,
                cron=cron,
                rrule=rrule,
                paused=paused,
                schedules=schedules,
                schedule=schedule,
                is_schedule_active=is_schedule_active,
                tags=tags,
                triggers=triggers,
                parameters=parameters or {},
                description=description,
                version=version,
                enforce_parameter_schema=enforce_parameter_schema,
                work_pool_name=work_pool_name,
                work_queue_name=work_queue_name,
                job_variables=job_variables,
            )
        else:
            return RunnerDeployment.from_flow(
                self,
                name=name,
                interval=interval,
                cron=cron,
                rrule=rrule,
                paused=paused,
                schedules=schedules,
                schedule=schedule,
                is_schedule_active=is_schedule_active,
                tags=tags,
                triggers=triggers,
                parameters=parameters or {},
                description=description,
                version=version,
                enforce_parameter_schema=enforce_parameter_schema,
                work_pool_name=work_pool_name,
                work_queue_name=work_queue_name,
                job_variables=job_variables,
                entrypoint_type=entrypoint_type,
            )

    def on_completion(
        self, fn: Callable[["Flow", FlowRun, State], None]
    ) -> Callable[["Flow", FlowRun, State], None]:
        self.on_completion_hooks.append(fn)
        return fn

    def on_cancellation(
        self, fn: Callable[["Flow", FlowRun, State], None]
    ) -> Callable[["Flow", FlowRun, State], None]:
        self.on_cancellation_hooks.append(fn)
        return fn

    def on_crashed(
        self, fn: Callable[["Flow", FlowRun, State], None]
    ) -> Callable[["Flow", FlowRun, State], None]:
        self.on_crashed_hooks.append(fn)
        return fn

    def on_running(
        self, fn: Callable[["Flow", FlowRun, State], None]
    ) -> Callable[["Flow", FlowRun, State], None]:
        self.on_running_hooks.append(fn)
        return fn

    def on_failure(
        self, fn: Callable[["Flow", FlowRun, State], None]
    ) -> Callable[["Flow", FlowRun, State], None]:
        self.on_failure_hooks.append(fn)
        return fn

    @sync_compatible
    async def serve(
        self,
        name: Optional[str] = None,
        interval: Optional[
            Union[
                Iterable[Union[int, float, datetime.timedelta]],
                int,
                float,
                datetime.timedelta,
            ]
        ] = None,
        cron: Optional[Union[Iterable[str], str]] = None,
        rrule: Optional[Union[Iterable[str], str]] = None,
        paused: Optional[bool] = None,
        schedules: Optional[List["FlexibleScheduleList"]] = None,
        schedule: Optional[SCHEDULE_TYPES] = None,
        is_schedule_active: Optional[bool] = None,
        triggers: Optional[List[Union[DeploymentTriggerTypes, TriggerTypes]]] = None,
        parameters: Optional[dict] = None,
        description: Optional[str] = None,
        tags: Optional[List[str]] = None,
        version: Optional[str] = None,
        enforce_parameter_schema: bool = True,
        pause_on_shutdown: bool = True,
        print_starting_message: bool = True,
        limit: Optional[int] = None,
        webserver: bool = False,
        entrypoint_type: EntrypointType = EntrypointType.FILE_PATH,
    ):
        """
        Creates a deployment for this flow and starts a runner to monitor for scheduled work.

        Args:
            name: The name to give the created deployment. Defaults to the name of the flow.
            interval: An interval on which to execute the deployment. Accepts a number or a
                timedelta object to create a single schedule. If a number is given, it will be
                interpreted as seconds. Also accepts an iterable of numbers or timedelta to create
                multiple schedules.
            cron: A cron schedule string of when to execute runs of this deployment.
                Also accepts an iterable of cron schedule strings to create multiple schedules.
            rrule: An rrule schedule string of when to execute runs of this deployment.
                Also accepts an iterable of rrule schedule strings to create multiple schedules.
            triggers: A list of triggers that will kick off runs of this deployment.
            paused: Whether or not to set this deployment as paused.
            schedules: A list of schedule objects defining when to execute runs of this deployment.
                Used to define multiple schedules or additional scheduling options like `timezone`.
            schedule: A schedule object defining when to execute runs of this deployment. Used to
                define additional scheduling options such as `timezone`.
            is_schedule_active: Whether or not to set the schedule for this deployment as active. If
                not provided when creating a deployment, the schedule will be set as active. If not
                provided when updating a deployment, the schedule's activation will not be changed.
            parameters: A dictionary of default parameter values to pass to runs of this deployment.
            description: A description for the created deployment. Defaults to the flow's
                description if not provided.
            tags: A list of tags to associate with the created deployment for organizational
                purposes.
            version: A version for the created deployment. Defaults to the flow's version.
            enforce_parameter_schema: Whether or not the Prefect API should enforce the
                parameter schema for the created deployment.
            pause_on_shutdown: If True, provided schedule will be paused when the serve function is stopped.
                If False, the schedules will continue running.
            print_starting_message: Whether or not to print the starting message when flow is served.
            limit: The maximum number of runs that can be executed concurrently.
            webserver: Whether or not to start a monitoring webserver for this flow.
            entrypoint_type: Type of entrypoint to use for the deployment. When using a module path
                entrypoint, ensure that the module will be importable in the execution environment.

        Examples:
            Serve a flow:

            ```python
            from prefect import flow

            @flow
            def my_flow(name):
                print(f"hello {name}")

            if __name__ == "__main__":
                my_flow.serve("example-deployment")
            ```

            Serve a flow and run it every hour:

            ```python
            from prefect import flow

            @flow
            def my_flow(name):
                print(f"hello {name}")

            if __name__ == "__main__":
                my_flow.serve("example-deployment", interval=3600)
            ```
        """
        from prefect.runner import Runner

        if not name:
            name = self.name
        else:
            # Handling for my_flow.serve(__file__)
            # Will set name to name of file where my_flow.serve() without the extension
            # Non filepath strings will pass through unchanged
            name = Path(name).stem

        runner = Runner(name=name, pause_on_shutdown=pause_on_shutdown, limit=limit)
        deployment_id = await runner.add_flow(
            self,
            name=name,
            triggers=triggers,
            interval=interval,
            cron=cron,
            rrule=rrule,
            paused=paused,
            schedules=schedules,
            schedule=schedule,
            is_schedule_active=is_schedule_active,
            parameters=parameters,
            description=description,
            tags=tags,
            version=version,
            enforce_parameter_schema=enforce_parameter_schema,
            entrypoint_type=entrypoint_type,
        )
        if print_starting_message:
            help_message = (
                f"[green]Your flow {self.name!r} is being served and polling for"
                " scheduled runs!\n[/]\nTo trigger a run for this flow, use the"
                " following command:\n[blue]\n\t$ prefect deployment run"
                f" '{self.name}/{name}'\n[/]"
            )
            if PREFECT_UI_URL:
                help_message += (
                    "\nYou can also run your flow via the Prefect UI:"
                    f" [blue]{PREFECT_UI_URL.value()}/deployments/deployment/{deployment_id}[/]\n"
                )

            console = Console()
            console.print(help_message, soft_wrap=True)
        await runner.start(webserver=webserver)

    @classmethod
    @sync_compatible
    async def from_source(
        cls: Type[F],
        source: Union[str, RunnerStorage, ReadableDeploymentStorage],
        entrypoint: str,
    ) -> F:
        """
        Loads a flow from a remote source.

        Args:
            source: Either a URL to a git repository or a storage object.
            entrypoint:  The path to a file containing a flow and the name of the flow function in
                the format `./path/to/file.py:flow_func_name`.

        Returns:
            A new `Flow` instance.

        Examples:
            Load a flow from a public git repository:


            ```python
            from prefect import flow
            from prefect.runner.storage import GitRepository
            from prefect.blocks.system import Secret

            my_flow = flow.from_source(
                source="https://github.com/org/repo.git",
                entrypoint="flows.py:my_flow",
            )

            my_flow()
            ```

            Load a flow from a private git repository using an access token stored in a `Secret` block:

            ```python
            from prefect import flow
            from prefect.runner.storage import GitRepository
            from prefect.blocks.system import Secret

            my_flow = flow.from_source(
                source=GitRepository(
                    url="https://github.com/org/repo.git",
                    credentials={"access_token": Secret.load("github-access-token")}
                ),
                entrypoint="flows.py:my_flow",
            )

            my_flow()
            ```
        """
        if isinstance(source, str):
            storage = create_storage_from_source(source)
        elif isinstance(source, RunnerStorage):
            storage = source
        elif hasattr(source, "get_directory"):
            storage = BlockStorageAdapter(source)
        else:
            raise TypeError(
                f"Unsupported source type {type(source).__name__!r}. Please provide a"
                " URL to remote storage or a storage object."
            )
        with tempfile.TemporaryDirectory() as tmpdir:
            if not isinstance(storage, LocalStorage):
                storage.set_base_path(Path(tmpdir))
                await storage.pull_code()
            storage.set_base_path(Path(tmpdir))
            await storage.pull_code()

            full_entrypoint = str(storage.destination / entrypoint)
            flow: "Flow" = await from_async.wait_for_call_in_new_thread(
                create_call(load_flow_from_entrypoint, full_entrypoint)
            )
            flow._storage = storage
            flow._entrypoint = entrypoint

        return flow

    @sync_compatible
    async def deploy(
        self,
        name: str,
        work_pool_name: Optional[str] = None,
        image: Optional[Union[str, DockerImage]] = None,
        build: bool = True,
        push: bool = True,
        work_queue_name: Optional[str] = None,
        job_variables: Optional[dict] = None,
        interval: Optional[Union[int, float, datetime.timedelta]] = None,
        cron: Optional[str] = None,
        rrule: Optional[str] = None,
        paused: Optional[bool] = None,
        schedules: Optional[List[DeploymentScheduleCreate]] = None,
        schedule: Optional[SCHEDULE_TYPES] = None,
        is_schedule_active: Optional[bool] = None,
        triggers: Optional[List[Union[DeploymentTriggerTypes, TriggerTypes]]] = None,
        parameters: Optional[dict] = None,
        description: Optional[str] = None,
        tags: Optional[List[str]] = None,
        version: Optional[str] = None,
        enforce_parameter_schema: bool = True,
        entrypoint_type: EntrypointType = EntrypointType.FILE_PATH,
        print_next_steps: bool = True,
        ignore_warnings: bool = False,
    ) -> UUID:
        """
        Deploys a flow to run on dynamic infrastructure via a work pool.

        By default, calling this method will build a Docker image for the flow, push it to a registry,
        and create a deployment via the Prefect API that will run the flow on the given schedule.

        If you want to use an existing image, you can pass `build=False` to skip building and pushing
        an image.

        Args:
            name: The name to give the created deployment.
            work_pool_name: The name of the work pool to use for this deployment. Defaults to
                the value of `PREFECT_DEFAULT_WORK_POOL_NAME`.
            image: The name of the Docker image to build, including the registry and
                repository. Pass a DockerImage instance to customize the Dockerfile used
                and build arguments.
            build: Whether or not to build a new image for the flow. If False, the provided
                image will be used as-is and pulled at runtime.
            push: Whether or not to skip pushing the built image to a registry.
            work_queue_name: The name of the work queue to use for this deployment's scheduled runs.
                If not provided the default work queue for the work pool will be used.
            job_variables: Settings used to override the values specified default base job template
                of the chosen work pool. Refer to the base job template of the chosen work pool for
                available settings.
            interval: An interval on which to execute the deployment. Accepts a number or a
                timedelta object to create a single schedule. If a number is given, it will be
                interpreted as seconds. Also accepts an iterable of numbers or timedelta to create
                multiple schedules.
            cron: A cron schedule string of when to execute runs of this deployment.
                Also accepts an iterable of cron schedule strings to create multiple schedules.
            rrule: An rrule schedule string of when to execute runs of this deployment.
                Also accepts an iterable of rrule schedule strings to create multiple schedules.
            triggers: A list of triggers that will kick off runs of this deployment.
            paused: Whether or not to set this deployment as paused.
            schedules: A list of schedule objects defining when to execute runs of this deployment.
                Used to define multiple schedules or additional scheduling options like `timezone`.
            schedule: A schedule object defining when to execute runs of this deployment. Used to
                define additional scheduling options like `timezone`.
            is_schedule_active: Whether or not to set the schedule for this deployment as active. If
                not provided when creating a deployment, the schedule will be set as active. If not
                provided when updating a deployment, the schedule's activation will not be changed.
            parameters: A dictionary of default parameter values to pass to runs of this deployment.
            description: A description for the created deployment. Defaults to the flow's
                description if not provided.
            tags: A list of tags to associate with the created deployment for organizational
                purposes.
            version: A version for the created deployment. Defaults to the flow's version.
            enforce_parameter_schema: Whether or not the Prefect API should enforce the
                parameter schema for the created deployment.
            entrypoint_type: Type of entrypoint to use for the deployment. When using a module path
                entrypoint, ensure that the module will be importable in the execution environment.
            print_next_steps_message: Whether or not to print a message with next steps
                after deploying the deployments.
            ignore_warnings: Whether or not to ignore warnings about the work pool type.

        Returns:
            The ID of the created/updated deployment.

        Examples:
            Deploy a local flow to a work pool:

            ```python
            from prefect import flow

            @flow
            def my_flow(name):
                print(f"hello {name}")

            if __name__ == "__main__":
                my_flow.deploy(
                    "example-deployment",
                    work_pool_name="my-work-pool",
                    image="my-repository/my-image:dev",
                )
            ```

            Deploy a remotely stored flow to a work pool:

            ```python
            from prefect import flow

            if __name__ == "__main__":
                flow.from_source(
                    source="https://github.com/org/repo.git",
                    entrypoint="flows.py:my_flow",
                ).deploy(
                    "example-deployment",
                    work_pool_name="my-work-pool",
                    image="my-repository/my-image:dev",
                )
            ```
        """
        work_pool_name = work_pool_name or PREFECT_DEFAULT_WORK_POOL_NAME.value()

        try:
            async with get_client() as client:
                work_pool = await client.read_work_pool(work_pool_name)
        except ObjectNotFound as exc:
            raise ValueError(
                f"Could not find work pool {work_pool_name!r}. Please create it before"
                " deploying this flow."
            ) from exc

        deployment = await self.to_deployment(
            name=name,
            interval=interval,
            cron=cron,
            rrule=rrule,
            schedules=schedules,
            paused=paused,
            schedule=schedule,
            is_schedule_active=is_schedule_active,
            triggers=triggers,
            parameters=parameters,
            description=description,
            tags=tags,
            version=version,
            enforce_parameter_schema=enforce_parameter_schema,
            work_queue_name=work_queue_name,
            job_variables=job_variables,
            entrypoint_type=entrypoint_type,
        )

        deployment_ids = await deploy(
            deployment,
            work_pool_name=work_pool_name,
            image=image,
            build=build,
            push=push,
            print_next_steps_message=False,
            ignore_warnings=ignore_warnings,
        )

        if print_next_steps:
            console = Console()
            if not work_pool.is_push_pool and not work_pool.is_managed_pool:
                console.print(
                    "\nTo execute flow runs from this deployment, start a worker in a"
                    " separate terminal that pulls work from the"
                    f" {work_pool_name!r} work pool:"
                )
                console.print(
                    f"\n\t$ prefect worker start --pool {work_pool_name!r}",
                    style="blue",
                )
            console.print(
                "\nTo schedule a run for this deployment, use the following command:"
            )
            console.print(
                f"\n\t$ prefect deployment run '{self.name}/{name}'\n",
                style="blue",
            )
            if PREFECT_UI_URL:
                message = (
                    "\nYou can also run your flow via the Prefect UI:"
                    f" [blue]{PREFECT_UI_URL.value()}/deployments/deployment/{deployment_ids[0]}[/]\n"
                )
                console.print(message, soft_wrap=True)

        return deployment_ids[0]

    @overload
    def __call__(self: "Flow[P, NoReturn]", *args: P.args, **kwargs: P.kwargs) -> None:
        # `NoReturn` matches if a type can't be inferred for the function which stops a
        # sync function from matching the `Coroutine` overload
        ...

    @overload
    def __call__(
        self: "Flow[P, Coroutine[Any, Any, T]]", *args: P.args, **kwargs: P.kwargs
    ) -> Awaitable[T]:
        ...

    @overload
    def __call__(
        self: "Flow[P, T]",
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> T:
        ...

    @overload
    def __call__(
        self: "Flow[P, T]",
        *args: P.args,
        return_state: Literal[True],
        **kwargs: P.kwargs,
    ) -> State[T]:
        ...

    def __call__(
        self,
        *args: "P.args",
        return_state: bool = False,
        wait_for: Optional[Iterable[PrefectFuture]] = None,
        **kwargs: "P.kwargs",
    ):
        """
        Run the flow and return its result.


        Flow parameter values must be serializable by Pydantic.

        If writing an async flow, this call must be awaited.

        This will create a new flow run in the API.

        Args:
            *args: Arguments to run the flow with.
            return_state: Return a Prefect State containing the result of the
                flow run.
            wait_for: Upstream task futures to wait for before starting the flow if called as a subflow
            **kwargs: Keyword arguments to run the flow with.

        Returns:
            If `return_state` is False, returns the result of the flow run.
            If `return_state` is True, returns the result of the flow run
                wrapped in a Prefect State which provides error handling.

        Examples:

            Define a flow

            >>> @flow
            >>> def my_flow(name):
            >>>     print(f"hello {name}")
            >>>     return f"goodbye {name}"

            Run a flow

            >>> my_flow("marvin")
            hello marvin
            "goodbye marvin"

            Run a flow with additional tags

            >>> from prefect import tags
            >>> with tags("db", "blue"):
            >>>     my_flow("foo")
        """
        from prefect.utilities.visualization import (
            get_task_viz_tracker,
            track_viz_task,
        )

        # Convert the call args/kwargs to a parameter dict
        parameters = get_call_parameters(self.fn, args, kwargs)

        return_type = "state" if return_state else "result"

        task_viz_tracker = get_task_viz_tracker()
        if task_viz_tracker:
            # this is a subflow, for now return a single task and do not go further
            # we can add support for exploring subflows for tasks in the future.
            return track_viz_task(self.isasync, self.name, parameters)

        from prefect.flow_engine import run_flow

        return run_flow(
            flow=self,
            parameters=parameters,
            wait_for=wait_for,
            return_type=return_type,
        )

    @sync_compatible
    async def visualize(self, *args, **kwargs):
        """
        Generates a graphviz object representing the current flow. In IPython notebooks,
        it's rendered inline, otherwise in a new window as a PNG.

        Raises:
            - ImportError: If `graphviz` isn't installed.
            - GraphvizExecutableNotFoundError: If the `dot` executable isn't found.
            - FlowVisualizationError: If the flow can't be visualized for any other reason.
        """
        from prefect.utilities.visualization import (
            FlowVisualizationError,
            GraphvizExecutableNotFoundError,
            GraphvizImportError,
            TaskVizTracker,
            VisualizationUnsupportedError,
            build_task_dependencies,
            visualize_task_dependencies,
        )

        if not PREFECT_UNIT_TEST_MODE:
            warnings.warn(
                "`flow.visualize()` will execute code inside of your flow that is not"
                " decorated with `@task` or `@flow`."
            )

        try:
            with TaskVizTracker() as tracker:
                if self.isasync:
                    await self.fn(*args, **kwargs)
                else:
                    self.fn(*args, **kwargs)

                graph = build_task_dependencies(tracker)

                visualize_task_dependencies(graph, self.name)

        except GraphvizImportError:
            raise
        except GraphvizExecutableNotFoundError:
            raise
        except VisualizationUnsupportedError:
            raise
        except FlowVisualizationError:
            raise
        except Exception as e:
            msg = (
                "It's possible you are trying to visualize a flow that contains "
                "code that directly interacts with the result of a task"
                " inside of the flow. \nTry passing a `viz_return_value` "
                "to the task decorator, e.g. `@task(viz_return_value=[1, 2, 3]).`"
            )

            new_exception = type(e)(str(e) + "\n" + msg)
            # Copy traceback information from the original exception
            new_exception.__traceback__ = e.__traceback__
            raise new_exception

__call__(*args, return_state=False, wait_for=None, **kwargs)

Run the flow and return its result.

Flow parameter values must be serializable by Pydantic.

If writing an async flow, this call must be awaited.

This will create a new flow run in the API.

Parameters:

Name Type Description Default
*args args

Arguments to run the flow with.

()
return_state bool

Return a Prefect State containing the result of the flow run.

False
wait_for Optional[Iterable[PrefectFuture]]

Upstream task futures to wait for before starting the flow if called as a subflow

None
**kwargs kwargs

Keyword arguments to run the flow with.

{}

Returns:

Type Description

If return_state is False, returns the result of the flow run.

If return_state is True, returns the result of the flow run wrapped in a Prefect State which provides error handling.

Define a flow

>>> @flow
>>> def my_flow(name):
>>>     print(f"hello {name}")
>>>     return f"goodbye {name}"

Run a flow

>>> my_flow("marvin")
hello marvin
"goodbye marvin"

Run a flow with additional tags

>>> from prefect import tags
>>> with tags("db", "blue"):
>>>     my_flow("foo")
Source code in src/prefect/flows.py
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
def __call__(
    self,
    *args: "P.args",
    return_state: bool = False,
    wait_for: Optional[Iterable[PrefectFuture]] = None,
    **kwargs: "P.kwargs",
):
    """
    Run the flow and return its result.


    Flow parameter values must be serializable by Pydantic.

    If writing an async flow, this call must be awaited.

    This will create a new flow run in the API.

    Args:
        *args: Arguments to run the flow with.
        return_state: Return a Prefect State containing the result of the
            flow run.
        wait_for: Upstream task futures to wait for before starting the flow if called as a subflow
        **kwargs: Keyword arguments to run the flow with.

    Returns:
        If `return_state` is False, returns the result of the flow run.
        If `return_state` is True, returns the result of the flow run
            wrapped in a Prefect State which provides error handling.

    Examples:

        Define a flow

        >>> @flow
        >>> def my_flow(name):
        >>>     print(f"hello {name}")
        >>>     return f"goodbye {name}"

        Run a flow

        >>> my_flow("marvin")
        hello marvin
        "goodbye marvin"

        Run a flow with additional tags

        >>> from prefect import tags
        >>> with tags("db", "blue"):
        >>>     my_flow("foo")
    """
    from prefect.utilities.visualization import (
        get_task_viz_tracker,
        track_viz_task,
    )

    # Convert the call args/kwargs to a parameter dict
    parameters = get_call_parameters(self.fn, args, kwargs)

    return_type = "state" if return_state else "result"

    task_viz_tracker = get_task_viz_tracker()
    if task_viz_tracker:
        # this is a subflow, for now return a single task and do not go further
        # we can add support for exploring subflows for tasks in the future.
        return track_viz_task(self.isasync, self.name, parameters)

    from prefect.flow_engine import run_flow

    return run_flow(
        flow=self,
        parameters=parameters,
        wait_for=wait_for,
        return_type=return_type,
    )

__get__(instance, owner)

Implement the descriptor protocol so that the flow can be used as an instance method. When an instance method is loaded, this method is called with the "self" instance as an argument. We return a copy of the flow with that instance bound to the flow's function.

Source code in src/prefect/flows.py
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
def __get__(self, instance, owner):
    """
    Implement the descriptor protocol so that the flow can be used as an instance method.
    When an instance method is loaded, this method is called with the "self" instance as
    an argument. We return a copy of the flow with that instance bound to the flow's function.
    """

    # if no instance is provided, it's being accessed on the class
    if instance is None:
        return self

    # if the flow is being accessed on an instance, bind the instance to the __prefect_self__ attribute
    # of the flow's function. This will allow it to be automatically added to the flow's parameters
    else:
        bound_flow = copy(self)
        bound_flow.fn.__prefect_self__ = instance
        return bound_flow

deploy(name, work_pool_name=None, image=None, build=True, push=True, work_queue_name=None, job_variables=None, interval=None, cron=None, rrule=None, paused=None, schedules=None, schedule=None, is_schedule_active=None, triggers=None, parameters=None, description=None, tags=None, version=None, enforce_parameter_schema=True, entrypoint_type=EntrypointType.FILE_PATH, print_next_steps=True, ignore_warnings=False) async

Deploys a flow to run on dynamic infrastructure via a work pool.

By default, calling this method will build a Docker image for the flow, push it to a registry, and create a deployment via the Prefect API that will run the flow on the given schedule.

If you want to use an existing image, you can pass build=False to skip building and pushing an image.

Parameters:

Name Type Description Default
name str

The name to give the created deployment.

required
work_pool_name Optional[str]

The name of the work pool to use for this deployment. Defaults to the value of PREFECT_DEFAULT_WORK_POOL_NAME.

None
image Optional[Union[str, DockerImage]]

The name of the Docker image to build, including the registry and repository. Pass a DockerImage instance to customize the Dockerfile used and build arguments.

None
build bool

Whether or not to build a new image for the flow. If False, the provided image will be used as-is and pulled at runtime.

True
push bool

Whether or not to skip pushing the built image to a registry.

True
work_queue_name Optional[str]

The name of the work queue to use for this deployment's scheduled runs. If not provided the default work queue for the work pool will be used.

None
job_variables Optional[dict]

Settings used to override the values specified default base job template of the chosen work pool. Refer to the base job template of the chosen work pool for available settings.

None
interval Optional[Union[int, float, timedelta]]

An interval on which to execute the deployment. Accepts a number or a timedelta object to create a single schedule. If a number is given, it will be interpreted as seconds. Also accepts an iterable of numbers or timedelta to create multiple schedules.

None
cron Optional[str]

A cron schedule string of when to execute runs of this deployment. Also accepts an iterable of cron schedule strings to create multiple schedules.

None
rrule Optional[str]

An rrule schedule string of when to execute runs of this deployment. Also accepts an iterable of rrule schedule strings to create multiple schedules.

None
triggers Optional[List[Union[DeploymentTriggerTypes, TriggerTypes]]]

A list of triggers that will kick off runs of this deployment.

None
paused Optional[bool]

Whether or not to set this deployment as paused.

None
schedules Optional[List[DeploymentScheduleCreate]]

A list of schedule objects defining when to execute runs of this deployment. Used to define multiple schedules or additional scheduling options like timezone.

None
schedule Optional[SCHEDULE_TYPES]

A schedule object defining when to execute runs of this deployment. Used to define additional scheduling options like timezone.

None
is_schedule_active Optional[bool]

Whether or not to set the schedule for this deployment as active. If not provided when creating a deployment, the schedule will be set as active. If not provided when updating a deployment, the schedule's activation will not be changed.

None
parameters Optional[dict]

A dictionary of default parameter values to pass to runs of this deployment.

None
description Optional[str]

A description for the created deployment. Defaults to the flow's description if not provided.

None
tags Optional[List[str]]

A list of tags to associate with the created deployment for organizational purposes.

None
version Optional[str]

A version for the created deployment. Defaults to the flow's version.

None
enforce_parameter_schema bool

Whether or not the Prefect API should enforce the parameter schema for the created deployment.

True
entrypoint_type EntrypointType

Type of entrypoint to use for the deployment. When using a module path entrypoint, ensure that the module will be importable in the execution environment.

FILE_PATH
print_next_steps_message

Whether or not to print a message with next steps after deploying the deployments.

required
ignore_warnings bool

Whether or not to ignore warnings about the work pool type.

False

Returns:

Type Description
UUID

The ID of the created/updated deployment.

Examples:

Deploy a local flow to a work pool:

from prefect import flow

@flow
def my_flow(name):
    print(f"hello {name}")

if __name__ == "__main__":
    my_flow.deploy(
        "example-deployment",
        work_pool_name="my-work-pool",
        image="my-repository/my-image:dev",
    )

Deploy a remotely stored flow to a work pool:

from prefect import flow

if __name__ == "__main__":
    flow.from_source(
        source="https://github.com/org/repo.git",
        entrypoint="flows.py:my_flow",
    ).deploy(
        "example-deployment",
        work_pool_name="my-work-pool",
        image="my-repository/my-image:dev",
    )
Source code in src/prefect/flows.py
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
@sync_compatible
async def deploy(
    self,
    name: str,
    work_pool_name: Optional[str] = None,
    image: Optional[Union[str, DockerImage]] = None,
    build: bool = True,
    push: bool = True,
    work_queue_name: Optional[str] = None,
    job_variables: Optional[dict] = None,
    interval: Optional[Union[int, float, datetime.timedelta]] = None,
    cron: Optional[str] = None,
    rrule: Optional[str] = None,
    paused: Optional[bool] = None,
    schedules: Optional[List[DeploymentScheduleCreate]] = None,
    schedule: Optional[SCHEDULE_TYPES] = None,
    is_schedule_active: Optional[bool] = None,
    triggers: Optional[List[Union[DeploymentTriggerTypes, TriggerTypes]]] = None,
    parameters: Optional[dict] = None,
    description: Optional[str] = None,
    tags: Optional[List[str]] = None,
    version: Optional[str] = None,
    enforce_parameter_schema: bool = True,
    entrypoint_type: EntrypointType = EntrypointType.FILE_PATH,
    print_next_steps: bool = True,
    ignore_warnings: bool = False,
) -> UUID:
    """
    Deploys a flow to run on dynamic infrastructure via a work pool.

    By default, calling this method will build a Docker image for the flow, push it to a registry,
    and create a deployment via the Prefect API that will run the flow on the given schedule.

    If you want to use an existing image, you can pass `build=False` to skip building and pushing
    an image.

    Args:
        name: The name to give the created deployment.
        work_pool_name: The name of the work pool to use for this deployment. Defaults to
            the value of `PREFECT_DEFAULT_WORK_POOL_NAME`.
        image: The name of the Docker image to build, including the registry and
            repository. Pass a DockerImage instance to customize the Dockerfile used
            and build arguments.
        build: Whether or not to build a new image for the flow. If False, the provided
            image will be used as-is and pulled at runtime.
        push: Whether or not to skip pushing the built image to a registry.
        work_queue_name: The name of the work queue to use for this deployment's scheduled runs.
            If not provided the default work queue for the work pool will be used.
        job_variables: Settings used to override the values specified default base job template
            of the chosen work pool. Refer to the base job template of the chosen work pool for
            available settings.
        interval: An interval on which to execute the deployment. Accepts a number or a
            timedelta object to create a single schedule. If a number is given, it will be
            interpreted as seconds. Also accepts an iterable of numbers or timedelta to create
            multiple schedules.
        cron: A cron schedule string of when to execute runs of this deployment.
            Also accepts an iterable of cron schedule strings to create multiple schedules.
        rrule: An rrule schedule string of when to execute runs of this deployment.
            Also accepts an iterable of rrule schedule strings to create multiple schedules.
        triggers: A list of triggers that will kick off runs of this deployment.
        paused: Whether or not to set this deployment as paused.
        schedules: A list of schedule objects defining when to execute runs of this deployment.
            Used to define multiple schedules or additional scheduling options like `timezone`.
        schedule: A schedule object defining when to execute runs of this deployment. Used to
            define additional scheduling options like `timezone`.
        is_schedule_active: Whether or not to set the schedule for this deployment as active. If
            not provided when creating a deployment, the schedule will be set as active. If not
            provided when updating a deployment, the schedule's activation will not be changed.
        parameters: A dictionary of default parameter values to pass to runs of this deployment.
        description: A description for the created deployment. Defaults to the flow's
            description if not provided.
        tags: A list of tags to associate with the created deployment for organizational
            purposes.
        version: A version for the created deployment. Defaults to the flow's version.
        enforce_parameter_schema: Whether or not the Prefect API should enforce the
            parameter schema for the created deployment.
        entrypoint_type: Type of entrypoint to use for the deployment. When using a module path
            entrypoint, ensure that the module will be importable in the execution environment.
        print_next_steps_message: Whether or not to print a message with next steps
            after deploying the deployments.
        ignore_warnings: Whether or not to ignore warnings about the work pool type.

    Returns:
        The ID of the created/updated deployment.

    Examples:
        Deploy a local flow to a work pool:

        ```python
        from prefect import flow

        @flow
        def my_flow(name):
            print(f"hello {name}")

        if __name__ == "__main__":
            my_flow.deploy(
                "example-deployment",
                work_pool_name="my-work-pool",
                image="my-repository/my-image:dev",
            )
        ```

        Deploy a remotely stored flow to a work pool:

        ```python
        from prefect import flow

        if __name__ == "__main__":
            flow.from_source(
                source="https://github.com/org/repo.git",
                entrypoint="flows.py:my_flow",
            ).deploy(
                "example-deployment",
                work_pool_name="my-work-pool",
                image="my-repository/my-image:dev",
            )
        ```
    """
    work_pool_name = work_pool_name or PREFECT_DEFAULT_WORK_POOL_NAME.value()

    try:
        async with get_client() as client:
            work_pool = await client.read_work_pool(work_pool_name)
    except ObjectNotFound as exc:
        raise ValueError(
            f"Could not find work pool {work_pool_name!r}. Please create it before"
            " deploying this flow."
        ) from exc

    deployment = await self.to_deployment(
        name=name,
        interval=interval,
        cron=cron,
        rrule=rrule,
        schedules=schedules,
        paused=paused,
        schedule=schedule,
        is_schedule_active=is_schedule_active,
        triggers=triggers,
        parameters=parameters,
        description=description,
        tags=tags,
        version=version,
        enforce_parameter_schema=enforce_parameter_schema,
        work_queue_name=work_queue_name,
        job_variables=job_variables,
        entrypoint_type=entrypoint_type,
    )

    deployment_ids = await deploy(
        deployment,
        work_pool_name=work_pool_name,
        image=image,
        build=build,
        push=push,
        print_next_steps_message=False,
        ignore_warnings=ignore_warnings,
    )

    if print_next_steps:
        console = Console()
        if not work_pool.is_push_pool and not work_pool.is_managed_pool:
            console.print(
                "\nTo execute flow runs from this deployment, start a worker in a"
                " separate terminal that pulls work from the"
                f" {work_pool_name!r} work pool:"
            )
            console.print(
                f"\n\t$ prefect worker start --pool {work_pool_name!r}",
                style="blue",
            )
        console.print(
            "\nTo schedule a run for this deployment, use the following command:"
        )
        console.print(
            f"\n\t$ prefect deployment run '{self.name}/{name}'\n",
            style="blue",
        )
        if PREFECT_UI_URL:
            message = (
                "\nYou can also run your flow via the Prefect UI:"
                f" [blue]{PREFECT_UI_URL.value()}/deployments/deployment/{deployment_ids[0]}[/]\n"
            )
            console.print(message, soft_wrap=True)

    return deployment_ids[0]

from_source(source, entrypoint) async classmethod

Loads a flow from a remote source.

Parameters:

Name Type Description Default
source Union[str, RunnerStorage, ReadableDeploymentStorage]

Either a URL to a git repository or a storage object.

required
entrypoint str

The path to a file containing a flow and the name of the flow function in the format ./path/to/file.py:flow_func_name.

required

Returns:

Type Description
F

A new Flow instance.

Examples:

Load a flow from a public git repository:

from prefect import flow
from prefect.runner.storage import GitRepository
from prefect.blocks.system import Secret

my_flow = flow.from_source(
    source="https://github.com/org/repo.git",
    entrypoint="flows.py:my_flow",
)

my_flow()

Load a flow from a private git repository using an access token stored in a Secret block:

from prefect import flow
from prefect.runner.storage import GitRepository
from prefect.blocks.system import Secret

my_flow = flow.from_source(
    source=GitRepository(
        url="https://github.com/org/repo.git",
        credentials={"access_token": Secret.load("github-access-token")}
    ),
    entrypoint="flows.py:my_flow",
)

my_flow()
Source code in src/prefect/flows.py
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
@classmethod
@sync_compatible
async def from_source(
    cls: Type[F],
    source: Union[str, RunnerStorage, ReadableDeploymentStorage],
    entrypoint: str,
) -> F:
    """
    Loads a flow from a remote source.

    Args:
        source: Either a URL to a git repository or a storage object.
        entrypoint:  The path to a file containing a flow and the name of the flow function in
            the format `./path/to/file.py:flow_func_name`.

    Returns:
        A new `Flow` instance.

    Examples:
        Load a flow from a public git repository:


        ```python
        from prefect import flow
        from prefect.runner.storage import GitRepository
        from prefect.blocks.system import Secret

        my_flow = flow.from_source(
            source="https://github.com/org/repo.git",
            entrypoint="flows.py:my_flow",
        )

        my_flow()
        ```

        Load a flow from a private git repository using an access token stored in a `Secret` block:

        ```python
        from prefect import flow
        from prefect.runner.storage import GitRepository
        from prefect.blocks.system import Secret

        my_flow = flow.from_source(
            source=GitRepository(
                url="https://github.com/org/repo.git",
                credentials={"access_token": Secret.load("github-access-token")}
            ),
            entrypoint="flows.py:my_flow",
        )

        my_flow()
        ```
    """
    if isinstance(source, str):
        storage = create_storage_from_source(source)
    elif isinstance(source, RunnerStorage):
        storage = source
    elif hasattr(source, "get_directory"):
        storage = BlockStorageAdapter(source)
    else:
        raise TypeError(
            f"Unsupported source type {type(source).__name__!r}. Please provide a"
            " URL to remote storage or a storage object."
        )
    with tempfile.TemporaryDirectory() as tmpdir:
        if not isinstance(storage, LocalStorage):
            storage.set_base_path(Path(tmpdir))
            await storage.pull_code()
        storage.set_base_path(Path(tmpdir))
        await storage.pull_code()

        full_entrypoint = str(storage.destination / entrypoint)
        flow: "Flow" = await from_async.wait_for_call_in_new_thread(
            create_call(load_flow_from_entrypoint, full_entrypoint)
        )
        flow._storage = storage
        flow._entrypoint = entrypoint

    return flow

serialize_parameters(parameters)

Convert parameters to a serializable form.

Uses FastAPI's jsonable_encoder to convert to JSON compatible objects without converting everything directly to a string. This maintains basic types like integers during API roundtrips.

Source code in src/prefect/flows.py
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
def serialize_parameters(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
    """
    Convert parameters to a serializable form.

    Uses FastAPI's `jsonable_encoder` to convert to JSON compatible objects without
    converting everything directly to a string. This maintains basic types like
    integers during API roundtrips.
    """
    serialized_parameters = {}
    for key, value in parameters.items():
        # do not serialize the bound self object
        if self.ismethod and value is self.fn.__prefect_self__:
            continue
        try:
            serialized_parameters[key] = jsonable_encoder(value)
        except (TypeError, ValueError):
            logger.debug(
                f"Parameter {key!r} for flow {self.name!r} is of unserializable "
                f"type {type(value).__name__!r} and will not be stored "
                "in the backend."
            )
            serialized_parameters[key] = f"<{type(value).__name__}>"
    return serialized_parameters

serve(name=None, interval=None, cron=None, rrule=None, paused=None, schedules=None, schedule=None, is_schedule_active=None, triggers=None, parameters=None, description=None, tags=None, version=None, enforce_parameter_schema=True, pause_on_shutdown=True, print_starting_message=True, limit=None, webserver=False, entrypoint_type=EntrypointType.FILE_PATH) async

Creates a deployment for this flow and starts a runner to monitor for scheduled work.

Parameters:

Name Type Description Default
name Optional[str]

The name to give the created deployment. Defaults to the name of the flow.

None
interval Optional[Union[Iterable[Union[int, float, timedelta]], int, float, timedelta]]

An interval on which to execute the deployment. Accepts a number or a timedelta object to create a single schedule. If a number is given, it will be interpreted as seconds. Also accepts an iterable of numbers or timedelta to create multiple schedules.

None
cron Optional[Union[Iterable[str], str]]

A cron schedule string of when to execute runs of this deployment. Also accepts an iterable of cron schedule strings to create multiple schedules.

None
rrule Optional[Union[Iterable[str], str]]

An rrule schedule string of when to execute runs of this deployment. Also accepts an iterable of rrule schedule strings to create multiple schedules.

None
triggers Optional[List[Union[DeploymentTriggerTypes, TriggerTypes]]]

A list of triggers that will kick off runs of this deployment.

None
paused Optional[bool]

Whether or not to set this deployment as paused.

None
schedules Optional[List[FlexibleScheduleList]]

A list of schedule objects defining when to execute runs of this deployment. Used to define multiple schedules or additional scheduling options like timezone.

None
schedule Optional[SCHEDULE_TYPES]

A schedule object defining when to execute runs of this deployment. Used to define additional scheduling options such as timezone.

None
is_schedule_active Optional[bool]

Whether or not to set the schedule for this deployment as active. If not provided when creating a deployment, the schedule will be set as active. If not provided when updating a deployment, the schedule's activation will not be changed.

None
parameters Optional[dict]

A dictionary of default parameter values to pass to runs of this deployment.

None
description Optional[str]

A description for the created deployment. Defaults to the flow's description if not provided.

None
tags Optional[List[str]]

A list of tags to associate with the created deployment for organizational purposes.

None
version Optional[str]

A version for the created deployment. Defaults to the flow's version.

None
enforce_parameter_schema bool

Whether or not the Prefect API should enforce the parameter schema for the created deployment.

True
pause_on_shutdown bool

If True, provided schedule will be paused when the serve function is stopped. If False, the schedules will continue running.

True
print_starting_message bool

Whether or not to print the starting message when flow is served.

True
limit Optional[int]

The maximum number of runs that can be executed concurrently.

None
webserver bool

Whether or not to start a monitoring webserver for this flow.

False
entrypoint_type EntrypointType

Type of entrypoint to use for the deployment. When using a module path entrypoint, ensure that the module will be importable in the execution environment.

FILE_PATH

Examples:

Serve a flow:

from prefect import flow

@flow
def my_flow(name):
    print(f"hello {name}")

if __name__ == "__main__":
    my_flow.serve("example-deployment")

Serve a flow and run it every hour:

from prefect import flow

@flow
def my_flow(name):
    print(f"hello {name}")

if __name__ == "__main__":
    my_flow.serve("example-deployment", interval=3600)
Source code in src/prefect/flows.py
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
@sync_compatible
async def serve(
    self,
    name: Optional[str] = None,
    interval: Optional[
        Union[
            Iterable[Union[int, float, datetime.timedelta]],
            int,
            float,
            datetime.timedelta,
        ]
    ] = None,
    cron: Optional[Union[Iterable[str], str]] = None,
    rrule: Optional[Union[Iterable[str], str]] = None,
    paused: Optional[bool] = None,
    schedules: Optional[List["FlexibleScheduleList"]] = None,
    schedule: Optional[SCHEDULE_TYPES] = None,
    is_schedule_active: Optional[bool] = None,
    triggers: Optional[List[Union[DeploymentTriggerTypes, TriggerTypes]]] = None,
    parameters: Optional[dict] = None,
    description: Optional[str] = None,
    tags: Optional[List[str]] = None,
    version: Optional[str] = None,
    enforce_parameter_schema: bool = True,
    pause_on_shutdown: bool = True,
    print_starting_message: bool = True,
    limit: Optional[int] = None,
    webserver: bool = False,
    entrypoint_type: EntrypointType = EntrypointType.FILE_PATH,
):
    """
    Creates a deployment for this flow and starts a runner to monitor for scheduled work.

    Args:
        name: The name to give the created deployment. Defaults to the name of the flow.
        interval: An interval on which to execute the deployment. Accepts a number or a
            timedelta object to create a single schedule. If a number is given, it will be
            interpreted as seconds. Also accepts an iterable of numbers or timedelta to create
            multiple schedules.
        cron: A cron schedule string of when to execute runs of this deployment.
            Also accepts an iterable of cron schedule strings to create multiple schedules.
        rrule: An rrule schedule string of when to execute runs of this deployment.
            Also accepts an iterable of rrule schedule strings to create multiple schedules.
        triggers: A list of triggers that will kick off runs of this deployment.
        paused: Whether or not to set this deployment as paused.
        schedules: A list of schedule objects defining when to execute runs of this deployment.
            Used to define multiple schedules or additional scheduling options like `timezone`.
        schedule: A schedule object defining when to execute runs of this deployment. Used to
            define additional scheduling options such as `timezone`.
        is_schedule_active: Whether or not to set the schedule for this deployment as active. If
            not provided when creating a deployment, the schedule will be set as active. If not
            provided when updating a deployment, the schedule's activation will not be changed.
        parameters: A dictionary of default parameter values to pass to runs of this deployment.
        description: A description for the created deployment. Defaults to the flow's
            description if not provided.
        tags: A list of tags to associate with the created deployment for organizational
            purposes.
        version: A version for the created deployment. Defaults to the flow's version.
        enforce_parameter_schema: Whether or not the Prefect API should enforce the
            parameter schema for the created deployment.
        pause_on_shutdown: If True, provided schedule will be paused when the serve function is stopped.
            If False, the schedules will continue running.
        print_starting_message: Whether or not to print the starting message when flow is served.
        limit: The maximum number of runs that can be executed concurrently.
        webserver: Whether or not to start a monitoring webserver for this flow.
        entrypoint_type: Type of entrypoint to use for the deployment. When using a module path
            entrypoint, ensure that the module will be importable in the execution environment.

    Examples:
        Serve a flow:

        ```python
        from prefect import flow

        @flow
        def my_flow(name):
            print(f"hello {name}")

        if __name__ == "__main__":
            my_flow.serve("example-deployment")
        ```

        Serve a flow and run it every hour:

        ```python
        from prefect import flow

        @flow
        def my_flow(name):
            print(f"hello {name}")

        if __name__ == "__main__":
            my_flow.serve("example-deployment", interval=3600)
        ```
    """
    from prefect.runner import Runner

    if not name:
        name = self.name
    else:
        # Handling for my_flow.serve(__file__)
        # Will set name to name of file where my_flow.serve() without the extension
        # Non filepath strings will pass through unchanged
        name = Path(name).stem

    runner = Runner(name=name, pause_on_shutdown=pause_on_shutdown, limit=limit)
    deployment_id = await runner.add_flow(
        self,
        name=name,
        triggers=triggers,
        interval=interval,
        cron=cron,
        rrule=rrule,
        paused=paused,
        schedules=schedules,
        schedule=schedule,
        is_schedule_active=is_schedule_active,
        parameters=parameters,
        description=description,
        tags=tags,
        version=version,
        enforce_parameter_schema=enforce_parameter_schema,
        entrypoint_type=entrypoint_type,
    )
    if print_starting_message:
        help_message = (
            f"[green]Your flow {self.name!r} is being served and polling for"
            " scheduled runs!\n[/]\nTo trigger a run for this flow, use the"
            " following command:\n[blue]\n\t$ prefect deployment run"
            f" '{self.name}/{name}'\n[/]"
        )
        if PREFECT_UI_URL:
            help_message += (
                "\nYou can also run your flow via the Prefect UI:"
                f" [blue]{PREFECT_UI_URL.value()}/deployments/deployment/{deployment_id}[/]\n"
            )

        console = Console()
        console.print(help_message, soft_wrap=True)
    await runner.start(webserver=webserver)

to_deployment(name, interval=None, cron=None, rrule=None, paused=None, schedules=None, schedule=None, is_schedule_active=None, parameters=None, triggers=None, description=None, tags=None, version=None, enforce_parameter_schema=True, work_pool_name=None, work_queue_name=None, job_variables=None, entrypoint_type=EntrypointType.FILE_PATH) async

Creates a runner deployment object for this flow.

Parameters:

Name Type Description Default
name str

The name to give the created deployment.

required
interval Optional[Union[Iterable[Union[int, float, timedelta]], int, float, timedelta]]

An interval on which to execute the new deployment. Accepts either a number or a timedelta object. If a number is given, it will be interpreted as seconds.

None
cron Optional[Union[Iterable[str], str]]

A cron schedule of when to execute runs of this deployment.

None
rrule Optional[Union[Iterable[str], str]]

An rrule schedule of when to execute runs of this deployment.

None
paused Optional[bool]

Whether or not to set this deployment as paused.

None
schedules Optional[List[FlexibleScheduleList]]

A list of schedule objects defining when to execute runs of this deployment. Used to define multiple schedules or additional scheduling options such as timezone.

None
schedule Optional[SCHEDULE_TYPES]

A schedule object defining when to execute runs of this deployment.

None
is_schedule_active Optional[bool]

Whether or not to set the schedule for this deployment as active. If not provided when creating a deployment, the schedule will be set as active. If not provided when updating a deployment, the schedule's activation will not be changed.

None
parameters Optional[dict]

A dictionary of default parameter values to pass to runs of this deployment.

None
triggers Optional[List[Union[DeploymentTriggerTypes, TriggerTypes]]]

A list of triggers that will kick off runs of this deployment.

None
description Optional[str]

A description for the created deployment. Defaults to the flow's description if not provided.

None
tags Optional[List[str]]

A list of tags to associate with the created deployment for organizational purposes.

None
version Optional[str]

A version for the created deployment. Defaults to the flow's version.

None
enforce_parameter_schema bool

Whether or not the Prefect API should enforce the parameter schema for the created deployment.

True
work_pool_name Optional[str]

The name of the work pool to use for this deployment.

None
work_queue_name Optional[str]

The name of the work queue to use for this deployment's scheduled runs. If not provided the default work queue for the work pool will be used.

None
job_variables Optional[Dict[str, Any]]

Settings used to override the values specified default base job template of the chosen work pool. Refer to the base job template of the chosen work pool for

None
entrypoint_type EntrypointType

Type of entrypoint to use for the deployment. When using a module path entrypoint, ensure that the module will be importable in the execution environment.

FILE_PATH

Examples:

Prepare two deployments and serve them:

from prefect import flow, serve

@flow
def my_flow(name):
    print(f"hello {name}")

@flow
def my_other_flow(name):
    print(f"goodbye {name}")

if __name__ == "__main__":
    hello_deploy = my_flow.to_deployment("hello", tags=["dev"])
    bye_deploy = my_other_flow.to_deployment("goodbye", tags=["dev"])
    serve(hello_deploy, bye_deploy)
Source code in src/prefect/flows.py
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
@sync_compatible
@deprecated_parameter(
    "schedule",
    start_date="Mar 2024",
    when=lambda p: p is not None,
    help="Use `schedules` instead.",
)
@deprecated_parameter(
    "is_schedule_active",
    start_date="Mar 2024",
    when=lambda p: p is not None,
    help="Use `paused` instead.",
)
async def to_deployment(
    self,
    name: str,
    interval: Optional[
        Union[
            Iterable[Union[int, float, datetime.timedelta]],
            int,
            float,
            datetime.timedelta,
        ]
    ] = None,
    cron: Optional[Union[Iterable[str], str]] = None,
    rrule: Optional[Union[Iterable[str], str]] = None,
    paused: Optional[bool] = None,
    schedules: Optional[List["FlexibleScheduleList"]] = None,
    schedule: Optional[SCHEDULE_TYPES] = None,
    is_schedule_active: Optional[bool] = None,
    parameters: Optional[dict] = None,
    triggers: Optional[List[Union[DeploymentTriggerTypes, TriggerTypes]]] = None,
    description: Optional[str] = None,
    tags: Optional[List[str]] = None,
    version: Optional[str] = None,
    enforce_parameter_schema: bool = True,
    work_pool_name: Optional[str] = None,
    work_queue_name: Optional[str] = None,
    job_variables: Optional[Dict[str, Any]] = None,
    entrypoint_type: EntrypointType = EntrypointType.FILE_PATH,
) -> "RunnerDeployment":
    """
    Creates a runner deployment object for this flow.

    Args:
        name: The name to give the created deployment.
        interval: An interval on which to execute the new deployment. Accepts either a number
            or a timedelta object. If a number is given, it will be interpreted as seconds.
        cron: A cron schedule of when to execute runs of this deployment.
        rrule: An rrule schedule of when to execute runs of this deployment.
        paused: Whether or not to set this deployment as paused.
        schedules: A list of schedule objects defining when to execute runs of this deployment.
            Used to define multiple schedules or additional scheduling options such as `timezone`.
        schedule: A schedule object defining when to execute runs of this deployment.
        is_schedule_active: Whether or not to set the schedule for this deployment as active. If
            not provided when creating a deployment, the schedule will be set as active. If not
            provided when updating a deployment, the schedule's activation will not be changed.
        parameters: A dictionary of default parameter values to pass to runs of this deployment.
        triggers: A list of triggers that will kick off runs of this deployment.
        description: A description for the created deployment. Defaults to the flow's
            description if not provided.
        tags: A list of tags to associate with the created deployment for organizational
            purposes.
        version: A version for the created deployment. Defaults to the flow's version.
        enforce_parameter_schema: Whether or not the Prefect API should enforce the
            parameter schema for the created deployment.
        work_pool_name: The name of the work pool to use for this deployment.
        work_queue_name: The name of the work queue to use for this deployment's scheduled runs.
            If not provided the default work queue for the work pool will be used.
        job_variables: Settings used to override the values specified default base job template
            of the chosen work pool. Refer to the base job template of the chosen work pool for
        entrypoint_type: Type of entrypoint to use for the deployment. When using a module path
            entrypoint, ensure that the module will be importable in the execution environment.

    Examples:
        Prepare two deployments and serve them:

        ```python
        from prefect import flow, serve

        @flow
        def my_flow(name):
            print(f"hello {name}")

        @flow
        def my_other_flow(name):
            print(f"goodbye {name}")

        if __name__ == "__main__":
            hello_deploy = my_flow.to_deployment("hello", tags=["dev"])
            bye_deploy = my_other_flow.to_deployment("goodbye", tags=["dev"])
            serve(hello_deploy, bye_deploy)
        ```
    """
    from prefect.deployments.runner import RunnerDeployment

    if not name.endswith(".py"):
        _raise_on_name_with_banned_characters(name)

    if self._storage and self._entrypoint:
        return await RunnerDeployment.from_storage(
            storage=self._storage,
            entrypoint=self._entrypoint,
            name=name,
            interval=interval,
            cron=cron,
            rrule=rrule,
            paused=paused,
            schedules=schedules,
            schedule=schedule,
            is_schedule_active=is_schedule_active,
            tags=tags,
            triggers=triggers,
            parameters=parameters or {},
            description=description,
            version=version,
            enforce_parameter_schema=enforce_parameter_schema,
            work_pool_name=work_pool_name,
            work_queue_name=work_queue_name,
            job_variables=job_variables,
        )
    else:
        return RunnerDeployment.from_flow(
            self,
            name=name,
            interval=interval,
            cron=cron,
            rrule=rrule,
            paused=paused,
            schedules=schedules,
            schedule=schedule,
            is_schedule_active=is_schedule_active,
            tags=tags,
            triggers=triggers,
            parameters=parameters or {},
            description=description,
            version=version,
            enforce_parameter_schema=enforce_parameter_schema,
            work_pool_name=work_pool_name,
            work_queue_name=work_queue_name,
            job_variables=job_variables,
            entrypoint_type=entrypoint_type,
        )

validate_parameters(parameters)

Validate parameters for compatibility with the flow by attempting to cast the inputs to the associated types specified by the function's type annotations.

Returns:

Type Description
Dict[str, Any]

A new dict of parameters that have been cast to the appropriate types

Raises:

Type Description
ParameterTypeError

if the provided parameters are not valid

Source code in src/prefect/flows.py
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
def validate_parameters(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
    """
    Validate parameters for compatibility with the flow by attempting to cast the inputs to the
    associated types specified by the function's type annotations.

    Returns:
        A new dict of parameters that have been cast to the appropriate types

    Raises:
        ParameterTypeError: if the provided parameters are not valid
    """
    args, kwargs = parameters_to_args_kwargs(self.fn, parameters)

    with warnings.catch_warnings():
        warnings.filterwarnings(
            "ignore", category=pydantic.warnings.PydanticDeprecatedSince20
        )
        has_v1_models = any(isinstance(o, V1BaseModel) for o in args) or any(
            isinstance(o, V1BaseModel) for o in kwargs.values()
        )

    has_v2_types = any(is_v2_type(o) for o in args) or any(
        is_v2_type(o) for o in kwargs.values()
    )

    if has_v1_models and has_v2_types:
        raise ParameterTypeError(
            "Cannot mix Pydantic v1 and v2 types as arguments to a flow."
        )

    if has_v1_models:
        validated_fn = V1ValidatedFunction(
            self.fn, config={"arbitrary_types_allowed": True}
        )
    else:
        validated_fn = V2ValidatedFunction(
            self.fn, config=pydantic.ConfigDict(arbitrary_types_allowed=True)
        )

    try:
        with warnings.catch_warnings():
            warnings.filterwarnings(
                "ignore", category=pydantic.warnings.PydanticDeprecatedSince20
            )
            model = validated_fn.init_model_instance(*args, **kwargs)
    except pydantic.ValidationError as exc:
        # We capture the pydantic exception and raise our own because the pydantic
        # exception is not picklable when using a cythonized pydantic installation
        logger.error(
            f"Parameter validation failed for flow {self.name!r}: {exc.errors()}"
            f"\nParameters: {parameters}"
        )
        raise ParameterTypeError.from_validation_error(exc) from None

    # Get the updated parameter dict with cast values from the model
    cast_parameters = {
        k: v
        for k, v in dict(model).items()
        if k in model.model_fields_set or model.model_fields[k].default_factory
    }
    return cast_parameters

visualize(*args, **kwargs) async

Generates a graphviz object representing the current flow. In IPython notebooks, it's rendered inline, otherwise in a new window as a PNG.

Raises:

Type Description
-ImportError

If graphviz isn't installed.

-GraphvizExecutableNotFoundError

If the dot executable isn't found.

-FlowVisualizationError

If the flow can't be visualized for any other reason.

Source code in src/prefect/flows.py
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
@sync_compatible
async def visualize(self, *args, **kwargs):
    """
    Generates a graphviz object representing the current flow. In IPython notebooks,
    it's rendered inline, otherwise in a new window as a PNG.

    Raises:
        - ImportError: If `graphviz` isn't installed.
        - GraphvizExecutableNotFoundError: If the `dot` executable isn't found.
        - FlowVisualizationError: If the flow can't be visualized for any other reason.
    """
    from prefect.utilities.visualization import (
        FlowVisualizationError,
        GraphvizExecutableNotFoundError,
        GraphvizImportError,
        TaskVizTracker,
        VisualizationUnsupportedError,
        build_task_dependencies,
        visualize_task_dependencies,
    )

    if not PREFECT_UNIT_TEST_MODE:
        warnings.warn(
            "`flow.visualize()` will execute code inside of your flow that is not"
            " decorated with `@task` or `@flow`."
        )

    try:
        with TaskVizTracker() as tracker:
            if self.isasync:
                await self.fn(*args, **kwargs)
            else:
                self.fn(*args, **kwargs)

            graph = build_task_dependencies(tracker)

            visualize_task_dependencies(graph, self.name)

    except GraphvizImportError:
        raise
    except GraphvizExecutableNotFoundError:
        raise
    except VisualizationUnsupportedError:
        raise
    except FlowVisualizationError:
        raise
    except Exception as e:
        msg = (
            "It's possible you are trying to visualize a flow that contains "
            "code that directly interacts with the result of a task"
            " inside of the flow. \nTry passing a `viz_return_value` "
            "to the task decorator, e.g. `@task(viz_return_value=[1, 2, 3]).`"
        )

        new_exception = type(e)(str(e) + "\n" + msg)
        # Copy traceback information from the original exception
        new_exception.__traceback__ = e.__traceback__
        raise new_exception

with_options(*, name=None, version=None, retries=None, retry_delay_seconds=None, description=None, flow_run_name=None, task_runner=None, timeout_seconds=None, validate_parameters=None, persist_result=NotSet, result_storage=NotSet, result_serializer=NotSet, cache_result_in_memory=None, log_prints=NotSet, on_completion=None, on_failure=None, on_cancellation=None, on_crashed=None, on_running=None)

Create a new flow from the current object, updating provided options.

Parameters:

Name Type Description Default
name Optional[str]

A new name for the flow.

None
version Optional[str]

A new version for the flow.

None
description Optional[str]

A new description for the flow.

None
flow_run_name Optional[Union[Callable[[], str], str]]

An optional name to distinguish runs of this flow; this name can be provided as a string template with the flow's parameters as variables, or a function that returns a string.

None
task_runner Union[Type[TaskRunner], TaskRunner, None]

A new task runner for the flow.

None
timeout_seconds Union[int, float, None]

A new number of seconds to fail the flow after if still running.

None
validate_parameters Optional[bool]

A new value indicating if flow calls should validate given parameters.

None
retries Optional[int]

A new number of times to retry on flow run failure.

None
retry_delay_seconds Optional[Union[int, float]]

A new number of seconds to wait before retrying the flow after failure. This is only applicable if retries is nonzero.

None
persist_result Optional[bool]

A new option for enabling or disabling result persistence.

NotSet
result_storage Optional[ResultStorage]

A new storage type to use for results.

NotSet
result_serializer Optional[ResultSerializer]

A new serializer to use for results.

NotSet
cache_result_in_memory Optional[bool]

A new value indicating if the flow's result should be cached in memory.

None
on_failure Optional[List[Callable[[Flow, FlowRun, State], None]]]

A new list of callables to run when the flow enters a failed state.

None
on_completion Optional[List[Callable[[Flow, FlowRun, State], None]]]

A new list of callables to run when the flow enters a completed state.

None
on_cancellation Optional[List[Callable[[Flow, FlowRun, State], None]]]

A new list of callables to run when the flow enters a cancelling state.

None
on_crashed Optional[List[Callable[[Flow, FlowRun, State], None]]]

A new list of callables to run when the flow enters a crashed state.

None
on_running Optional[List[Callable[[Flow, FlowRun, State], None]]]

A new list of callables to run when the flow enters a running state.

None

Returns:

Type Description
Self

A new Flow instance.

Create a new flow from an existing flow and update the name:

>>> @flow(name="My flow")
>>> def my_flow():
>>>     return 1
>>>
>>> new_flow = my_flow.with_options(name="My new flow")

Create a new flow from an existing flow, update the task runner, and call
it without an intermediate variable:

>>> from prefect.task_runners import ThreadPoolTaskRunner
>>>
>>> @flow
>>> def my_flow(x, y):
>>>     return x + y
>>>
>>> state = my_flow.with_options(task_runner=ThreadPoolTaskRunner)(1, 3)
>>> assert state.result() == 4
Source code in src/prefect/flows.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
def with_options(
    self,
    *,
    name: Optional[str] = None,
    version: Optional[str] = None,
    retries: Optional[int] = None,
    retry_delay_seconds: Optional[Union[int, float]] = None,
    description: Optional[str] = None,
    flow_run_name: Optional[Union[Callable[[], str], str]] = None,
    task_runner: Union[Type[TaskRunner], TaskRunner, None] = None,
    timeout_seconds: Union[int, float, None] = None,
    validate_parameters: Optional[bool] = None,
    persist_result: Optional[bool] = NotSet,  # type: ignore
    result_storage: Optional[ResultStorage] = NotSet,  # type: ignore
    result_serializer: Optional[ResultSerializer] = NotSet,  # type: ignore
    cache_result_in_memory: Optional[bool] = None,
    log_prints: Optional[bool] = NotSet,  # type: ignore
    on_completion: Optional[
        List[Callable[[FlowSchema, FlowRun, State], None]]
    ] = None,
    on_failure: Optional[List[Callable[[FlowSchema, FlowRun, State], None]]] = None,
    on_cancellation: Optional[
        List[Callable[[FlowSchema, FlowRun, State], None]]
    ] = None,
    on_crashed: Optional[List[Callable[[FlowSchema, FlowRun, State], None]]] = None,
    on_running: Optional[List[Callable[[FlowSchema, FlowRun, State], None]]] = None,
) -> Self:
    """
    Create a new flow from the current object, updating provided options.

    Args:
        name: A new name for the flow.
        version: A new version for the flow.
        description: A new description for the flow.
        flow_run_name: An optional name to distinguish runs of this flow; this name
            can be provided as a string template with the flow's parameters as variables,
            or a function that returns a string.
        task_runner: A new task runner for the flow.
        timeout_seconds: A new number of seconds to fail the flow after if still
            running.
        validate_parameters: A new value indicating if flow calls should validate
            given parameters.
        retries: A new number of times to retry on flow run failure.
        retry_delay_seconds: A new number of seconds to wait before retrying the
            flow after failure. This is only applicable if `retries` is nonzero.
        persist_result: A new option for enabling or disabling result persistence.
        result_storage: A new storage type to use for results.
        result_serializer: A new serializer to use for results.
        cache_result_in_memory: A new value indicating if the flow's result should
            be cached in memory.
        on_failure: A new list of callables to run when the flow enters a failed state.
        on_completion: A new list of callables to run when the flow enters a completed state.
        on_cancellation: A new list of callables to run when the flow enters a cancelling state.
        on_crashed: A new list of callables to run when the flow enters a crashed state.
        on_running: A new list of callables to run when the flow enters a running state.

    Returns:
        A new `Flow` instance.

    Examples:

        Create a new flow from an existing flow and update the name:

        >>> @flow(name="My flow")
        >>> def my_flow():
        >>>     return 1
        >>>
        >>> new_flow = my_flow.with_options(name="My new flow")

        Create a new flow from an existing flow, update the task runner, and call
        it without an intermediate variable:

        >>> from prefect.task_runners import ThreadPoolTaskRunner
        >>>
        >>> @flow
        >>> def my_flow(x, y):
        >>>     return x + y
        >>>
        >>> state = my_flow.with_options(task_runner=ThreadPoolTaskRunner)(1, 3)
        >>> assert state.result() == 4
    """
    new_flow = Flow(
        fn=self.fn,
        name=name or self.name,
        description=description or self.description,
        flow_run_name=flow_run_name or self.flow_run_name,
        version=version or self.version,
        task_runner=task_runner or self.task_runner,
        retries=retries if retries is not None else self.retries,
        retry_delay_seconds=(
            retry_delay_seconds
            if retry_delay_seconds is not None
            else self.retry_delay_seconds
        ),
        timeout_seconds=(
            timeout_seconds if timeout_seconds is not None else self.timeout_seconds
        ),
        validate_parameters=(
            validate_parameters
            if validate_parameters is not None
            else self.should_validate_parameters
        ),
        persist_result=(
            persist_result if persist_result is not NotSet else self.persist_result
        ),
        result_storage=(
            result_storage if result_storage is not NotSet else self.result_storage
        ),
        result_serializer=(
            result_serializer
            if result_serializer is not NotSet
            else self.result_serializer
        ),
        cache_result_in_memory=(
            cache_result_in_memory
            if cache_result_in_memory is not None
            else self.cache_result_in_memory
        ),
        log_prints=log_prints if log_prints is not NotSet else self.log_prints,
        on_completion=on_completion or self.on_completion_hooks,
        on_failure=on_failure or self.on_failure_hooks,
        on_cancellation=on_cancellation or self.on_cancellation_hooks,
        on_crashed=on_crashed or self.on_crashed_hooks,
        on_running=on_running or self.on_running_hooks,
    )
    new_flow._storage = self._storage
    new_flow._entrypoint = self._entrypoint
    return new_flow

Manifest

Bases: BaseModel

A JSON representation of a flow.

Source code in src/prefect/manifests.py
12
13
14
15
16
17
18
19
20
21
class Manifest(BaseModel):
    """A JSON representation of a flow."""

    flow_name: str = Field(default=..., description="The name of the flow.")
    import_path: str = Field(
        default=..., description="The relative import path for the flow."
    )
    parameter_openapi_schema: ParameterSchema = Field(
        default=..., description="The OpenAPI schema of the flow's parameters."
    )

State

Bases: ObjectBaseModel, Generic[R]

The state of a run.

Source code in src/prefect/client/schemas/objects.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
class State(ObjectBaseModel, Generic[R]):
    """
    The state of a run.
    """

    type: StateType
    name: Optional[str] = Field(default=None)
    timestamp: DateTime = Field(default_factory=lambda: pendulum.now("UTC"))
    message: Optional[str] = Field(default=None, examples=["Run started"])
    state_details: StateDetails = Field(default_factory=StateDetails)
    data: Union["BaseResult[R]", Any] = Field(
        default=None,
    )

    @overload
    def result(self: "State[R]", raise_on_failure: bool = True) -> R:
        ...

    @overload
    def result(self: "State[R]", raise_on_failure: bool = False) -> Union[R, Exception]:
        ...

    def result(
        self,
        raise_on_failure: bool = True,
        fetch: Optional[bool] = None,
        retry_result_failure: bool = True,
    ) -> Union[R, Exception]:
        """
        Retrieve the result attached to this state.

        Args:
            raise_on_failure: a boolean specifying whether to raise an exception
                if the state is of type `FAILED` and the underlying data is an exception
            fetch: a boolean specifying whether to resolve references to persisted
                results into data. For synchronous users, this defaults to `True`.
                For asynchronous users, this defaults to `False` for backwards
                compatibility.
            retry_result_failure: a boolean specifying whether to retry on failures to
                load the result from result storage

        Raises:
            TypeError: If the state is failed but the result is not an exception.

        Returns:
            The result of the run

        Examples:
            >>> from prefect import flow, task
            >>> @task
            >>> def my_task(x):
            >>>     return x

            Get the result from a task future in a flow

            >>> @flow
            >>> def my_flow():
            >>>     future = my_task("hello")
            >>>     state = future.wait()
            >>>     result = state.result()
            >>>     print(result)
            >>> my_flow()
            hello

            Get the result from a flow state

            >>> @flow
            >>> def my_flow():
            >>>     return "hello"
            >>> my_flow(return_state=True).result()
            hello

            Get the result from a failed state

            >>> @flow
            >>> def my_flow():
            >>>     raise ValueError("oh no!")
            >>> state = my_flow(return_state=True)  # Error is wrapped in FAILED state
            >>> state.result()  # Raises `ValueError`

            Get the result from a failed state without erroring

            >>> @flow
            >>> def my_flow():
            >>>     raise ValueError("oh no!")
            >>> state = my_flow(return_state=True)
            >>> result = state.result(raise_on_failure=False)
            >>> print(result)
            ValueError("oh no!")


            Get the result from a flow state in an async context

            >>> @flow
            >>> async def my_flow():
            >>>     return "hello"
            >>> state = await my_flow(return_state=True)
            >>> await state.result()
            hello
        """
        from prefect.states import get_state_result

        return get_state_result(
            self,
            raise_on_failure=raise_on_failure,
            fetch=fetch,
            retry_result_failure=retry_result_failure,
        )

    def to_state_create(self):
        """
        Convert this state to a `StateCreate` type which can be used to set the state of
        a run in the API.

        This method will drop this state's `data` if it is not a result type. Only
        results should be sent to the API. Other data is only available locally.
        """
        from prefect.client.schemas.actions import StateCreate
        from prefect.results import BaseResult

        return StateCreate(
            type=self.type,
            name=self.name,
            message=self.message,
            data=self.data if isinstance(self.data, BaseResult) else None,
            state_details=self.state_details,
        )

    @model_validator(mode="after")
    def default_name_from_type(self) -> Self:
        """If a name is not provided, use the type"""
        # if `type` is not in `values` it means the `type` didn't pass its own
        # validation check and an error will be raised after this function is called
        name = self.name
        if name is None and self.type:
            self.name = " ".join([v.capitalize() for v in self.type.value.split("_")])
        return self

    @model_validator(mode="after")
    def default_scheduled_start_time(self) -> Self:
        if self.type == StateType.SCHEDULED:
            if not self.state_details.scheduled_time:
                self.state_details.scheduled_time = DateTime.now("utc")
        return self

    def is_scheduled(self) -> bool:
        return self.type == StateType.SCHEDULED

    def is_pending(self) -> bool:
        return self.type == StateType.PENDING

    def is_running(self) -> bool:
        return self.type == StateType.RUNNING

    def is_completed(self) -> bool:
        return self.type == StateType.COMPLETED

    def is_failed(self) -> bool:
        return self.type == StateType.FAILED

    def is_crashed(self) -> bool:
        return self.type == StateType.CRASHED

    def is_cancelled(self) -> bool:
        return self.type == StateType.CANCELLED

    def is_cancelling(self) -> bool:
        return self.type == StateType.CANCELLING

    def is_final(self) -> bool:
        return self.type in TERMINAL_STATES

    def is_paused(self) -> bool:
        return self.type == StateType.PAUSED

    def model_copy(
        self, *, update: Optional[Dict[str, Any]] = None, deep: bool = False
    ):
        """
        Copying API models should return an object that could be inserted into the
        database again. The 'timestamp' is reset using the default factory.
        """
        update = update or {}
        update.setdefault("timestamp", self.model_fields["timestamp"].get_default())
        return super().model_copy(update=update, deep=deep)

    def fresh_copy(self, **kwargs) -> Self:
        """
        Return a fresh copy of the state with a new ID.
        """
        return self.model_copy(
            update={
                "id": uuid4(),
                "created": pendulum.now("utc"),
                "updated": pendulum.now("utc"),
                "timestamp": pendulum.now("utc"),
            },
            **kwargs,
        )

    def __repr__(self) -> str:
        """
        Generates a complete state representation appropriate for introspection
        and debugging, including the result:

        `MyCompletedState(message="my message", type=COMPLETED, result=...)`
        """
        result = self.data

        display = dict(
            message=repr(self.message),
            type=str(self.type.value),
            result=repr(result),
        )

        return f"{self.name}({', '.join(f'{k}={v}' for k, v in display.items())})"

    def __str__(self) -> str:
        """
        Generates a simple state representation appropriate for logging:

        `MyCompletedState("my message", type=COMPLETED)`
        """

        display = []

        if self.message:
            display.append(repr(self.message))

        if self.type.value.lower() != self.name.lower():
            display.append(f"type={self.type.value}")

        return f"{self.name}({', '.join(display)})"

    def __hash__(self) -> int:
        return hash(
            (
                getattr(self.state_details, "flow_run_id", None),
                getattr(self.state_details, "task_run_id", None),
                self.timestamp,
                self.type,
            )
        )

__repr__()

Generates a complete state representation appropriate for introspection and debugging, including the result:

MyCompletedState(message="my message", type=COMPLETED, result=...)

Source code in src/prefect/client/schemas/objects.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
def __repr__(self) -> str:
    """
    Generates a complete state representation appropriate for introspection
    and debugging, including the result:

    `MyCompletedState(message="my message", type=COMPLETED, result=...)`
    """
    result = self.data

    display = dict(
        message=repr(self.message),
        type=str(self.type.value),
        result=repr(result),
    )

    return f"{self.name}({', '.join(f'{k}={v}' for k, v in display.items())})"

__str__()

Generates a simple state representation appropriate for logging:

MyCompletedState("my message", type=COMPLETED)

Source code in src/prefect/client/schemas/objects.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
def __str__(self) -> str:
    """
    Generates a simple state representation appropriate for logging:

    `MyCompletedState("my message", type=COMPLETED)`
    """

    display = []

    if self.message:
        display.append(repr(self.message))

    if self.type.value.lower() != self.name.lower():
        display.append(f"type={self.type.value}")

    return f"{self.name}({', '.join(display)})"

default_name_from_type()

If a name is not provided, use the type

Source code in src/prefect/client/schemas/objects.py
287
288
289
290
291
292
293
294
295
@model_validator(mode="after")
def default_name_from_type(self) -> Self:
    """If a name is not provided, use the type"""
    # if `type` is not in `values` it means the `type` didn't pass its own
    # validation check and an error will be raised after this function is called
    name = self.name
    if name is None and self.type:
        self.name = " ".join([v.capitalize() for v in self.type.value.split("_")])
    return self

fresh_copy(**kwargs)

Return a fresh copy of the state with a new ID.

Source code in src/prefect/client/schemas/objects.py
345
346
347
348
349
350
351
352
353
354
355
356
357
def fresh_copy(self, **kwargs) -> Self:
    """
    Return a fresh copy of the state with a new ID.
    """
    return self.model_copy(
        update={
            "id": uuid4(),
            "created": pendulum.now("utc"),
            "updated": pendulum.now("utc"),
            "timestamp": pendulum.now("utc"),
        },
        **kwargs,
    )

model_copy(*, update=None, deep=False)

Copying API models should return an object that could be inserted into the database again. The 'timestamp' is reset using the default factory.

Source code in src/prefect/client/schemas/objects.py
334
335
336
337
338
339
340
341
342
343
def model_copy(
    self, *, update: Optional[Dict[str, Any]] = None, deep: bool = False
):
    """
    Copying API models should return an object that could be inserted into the
    database again. The 'timestamp' is reset using the default factory.
    """
    update = update or {}
    update.setdefault("timestamp", self.model_fields["timestamp"].get_default())
    return super().model_copy(update=update, deep=deep)

result(raise_on_failure=True, fetch=None, retry_result_failure=True)

Retrieve the result attached to this state.

Parameters:

Name Type Description Default
raise_on_failure bool

a boolean specifying whether to raise an exception if the state is of type FAILED and the underlying data is an exception

True
fetch Optional[bool]

a boolean specifying whether to resolve references to persisted results into data. For synchronous users, this defaults to True. For asynchronous users, this defaults to False for backwards compatibility.

None
retry_result_failure bool

a boolean specifying whether to retry on failures to load the result from result storage

True

Raises:

Type Description
TypeError

If the state is failed but the result is not an exception.

Returns:

Type Description
Union[R, Exception]

The result of the run

Examples:

>>> from prefect import flow, task
>>> @task
>>> def my_task(x):
>>>     return x

Get the result from a task future in a flow

>>> @flow
>>> def my_flow():
>>>     future = my_task("hello")
>>>     state = future.wait()
>>>     result = state.result()
>>>     print(result)
>>> my_flow()
hello

Get the result from a flow state

>>> @flow
>>> def my_flow():
>>>     return "hello"
>>> my_flow(return_state=True).result()
hello

Get the result from a failed state

>>> @flow
>>> def my_flow():
>>>     raise ValueError("oh no!")
>>> state = my_flow(return_state=True)  # Error is wrapped in FAILED state
>>> state.result()  # Raises `ValueError`

Get the result from a failed state without erroring

>>> @flow
>>> def my_flow():
>>>     raise ValueError("oh no!")
>>> state = my_flow(return_state=True)
>>> result = state.result(raise_on_failure=False)
>>> print(result)
ValueError("oh no!")

Get the result from a flow state in an async context

>>> @flow
>>> async def my_flow():
>>>     return "hello"
>>> state = await my_flow(return_state=True)
>>> await state.result()
hello
Source code in src/prefect/client/schemas/objects.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
def result(
    self,
    raise_on_failure: bool = True,
    fetch: Optional[bool] = None,
    retry_result_failure: bool = True,
) -> Union[R, Exception]:
    """
    Retrieve the result attached to this state.

    Args:
        raise_on_failure: a boolean specifying whether to raise an exception
            if the state is of type `FAILED` and the underlying data is an exception
        fetch: a boolean specifying whether to resolve references to persisted
            results into data. For synchronous users, this defaults to `True`.
            For asynchronous users, this defaults to `False` for backwards
            compatibility.
        retry_result_failure: a boolean specifying whether to retry on failures to
            load the result from result storage

    Raises:
        TypeError: If the state is failed but the result is not an exception.

    Returns:
        The result of the run

    Examples:
        >>> from prefect import flow, task
        >>> @task
        >>> def my_task(x):
        >>>     return x

        Get the result from a task future in a flow

        >>> @flow
        >>> def my_flow():
        >>>     future = my_task("hello")
        >>>     state = future.wait()
        >>>     result = state.result()
        >>>     print(result)
        >>> my_flow()
        hello

        Get the result from a flow state

        >>> @flow
        >>> def my_flow():
        >>>     return "hello"
        >>> my_flow(return_state=True).result()
        hello

        Get the result from a failed state

        >>> @flow
        >>> def my_flow():
        >>>     raise ValueError("oh no!")
        >>> state = my_flow(return_state=True)  # Error is wrapped in FAILED state
        >>> state.result()  # Raises `ValueError`

        Get the result from a failed state without erroring

        >>> @flow
        >>> def my_flow():
        >>>     raise ValueError("oh no!")
        >>> state = my_flow(return_state=True)
        >>> result = state.result(raise_on_failure=False)
        >>> print(result)
        ValueError("oh no!")


        Get the result from a flow state in an async context

        >>> @flow
        >>> async def my_flow():
        >>>     return "hello"
        >>> state = await my_flow(return_state=True)
        >>> await state.result()
        hello
    """
    from prefect.states import get_state_result

    return get_state_result(
        self,
        raise_on_failure=raise_on_failure,
        fetch=fetch,
        retry_result_failure=retry_result_failure,
    )

to_state_create()

Convert this state to a StateCreate type which can be used to set the state of a run in the API.

This method will drop this state's data if it is not a result type. Only results should be sent to the API. Other data is only available locally.

Source code in src/prefect/client/schemas/objects.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def to_state_create(self):
    """
    Convert this state to a `StateCreate` type which can be used to set the state of
    a run in the API.

    This method will drop this state's `data` if it is not a result type. Only
    results should be sent to the API. Other data is only available locally.
    """
    from prefect.client.schemas.actions import StateCreate
    from prefect.results import BaseResult

    return StateCreate(
        type=self.type,
        name=self.name,
        message=self.message,
        data=self.data if isinstance(self.data, BaseResult) else None,
        state_details=self.state_details,
    )

Task

Bases: Generic[P, R]

A Prefect task definition.

Note

We recommend using the @task decorator for most use-cases.

Wraps a function with an entrypoint to the Prefect engine. Calling this class within a flow function creates a new task run.

To preserve the input and output types, we use the generic type variables P and R for "Parameters" and "Returns" respectively.

Parameters:

Name Type Description Default
fn Callable[P, R]

The function defining the task.

required
name Optional[str]

An optional name for the task; if not provided, the name will be inferred from the given function.

None
description Optional[str]

An optional string description for the task.

None
tags Optional[Iterable[str]]

An optional set of tags to be associated with runs of this task. These tags are combined with any tags defined by a prefect.tags context at task runtime.

None
version Optional[str]

An optional string specifying the version of this task definition

None
cache_policy Optional[CachePolicy]

A cache policy that determines the level of caching for this task

NotSet
cache_key_fn Optional[Callable[[TaskRunContext, Dict[str, Any]], Optional[str]]]

An optional callable that, given the task run context and call parameters, generates a string key; if the key matches a previous completed state, that state result will be restored instead of running the task again.

None
cache_expiration Optional[timedelta]

An optional amount of time indicating how long cached states for this task should be restorable; if not provided, cached states will never expire.

None
task_run_name Optional[Union[Callable[[], str], str]]

An optional name to distinguish runs of this task; this name can be provided as a string template with the task's keyword arguments as variables, or a function that returns a string.

None
retries Optional[int]

An optional number of times to retry on task run failure.

None
retry_delay_seconds Optional[Union[float, int, List[float], Callable[[int], List[float]]]]

Optionally configures how long to wait before retrying the task after failure. This is only applicable if retries is nonzero. This setting can either be a number of seconds, a list of retry delays, or a callable that, given the total number of retries, generates a list of retry delays. If a number of seconds, that delay will be applied to all retries. If a list, each retry will wait for the corresponding delay before retrying. When passing a callable or a list, the number of configured retry delays cannot exceed 50.

None
retry_jitter_factor Optional[float]

An optional factor that defines the factor to which a retry can be jittered in order to avoid a "thundering herd".

None
persist_result Optional[bool]

A toggle indicating whether the result of this task should be persisted to result storage. Defaults to None, which indicates that the global default should be used (which is True by default).

None
result_storage Optional[ResultStorage]

An optional block to use to persist the result of this task. Defaults to the value set in the flow the task is called in.

None
result_storage_key Optional[str]

An optional key to store the result in storage at when persisted. Defaults to a unique identifier.

None
result_serializer Optional[ResultSerializer]

An optional serializer to use to serialize the result of this task for persistence. Defaults to the value set in the flow the task is called in.

None
timeout_seconds Union[int, float, None]

An optional number of seconds indicating a maximum runtime for the task. If the task exceeds this runtime, it will be marked as failed.

None
log_prints Optional[bool]

If set, print statements in the task will be redirected to the Prefect logger for the task run. Defaults to None, which indicates that the value from the flow should be used.

False
refresh_cache Optional[bool]

If set, cached results for the cache key are not used. Defaults to None, which indicates that a cached result from a previous execution with matching cache key is used.

None
on_failure Optional[List[Callable[[Task, TaskRun, State], None]]]

An optional list of callables to run when the task enters a failed state.

None
on_completion Optional[List[Callable[[Task, TaskRun, State], None]]]

An optional list of callables to run when the task enters a completed state.

None
on_commit Optional[List[Callable[[Transaction], None]]]

An optional list of callables to run when the task's idempotency record is committed.

None
on_rollback Optional[List[Callable[[Transaction], None]]]

An optional list of callables to run when the task rolls back.

None
retry_condition_fn Optional[Callable[[Task, TaskRun, State], bool]]

An optional callable run when a task run returns a Failed state. Should return True if the task should continue to its retry policy (e.g. retries=3), and False if the task should end as failed. Defaults to None, indicating the task should always continue to its retry policy.

None
viz_return_value Optional[Any]

An optional value to return when the task dependency tree is visualized.

None
Source code in src/prefect/tasks.py
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
class Task(Generic[P, R]):
    """
    A Prefect task definition.

    !!! note
        We recommend using [the `@task` decorator][prefect.tasks.task] for most use-cases.

    Wraps a function with an entrypoint to the Prefect engine. Calling this class within a flow function
    creates a new task run.

    To preserve the input and output types, we use the generic type variables P and R for "Parameters" and
    "Returns" respectively.

    Args:
        fn: The function defining the task.
        name: An optional name for the task; if not provided, the name will be inferred
            from the given function.
        description: An optional string description for the task.
        tags: An optional set of tags to be associated with runs of this task. These
            tags are combined with any tags defined by a `prefect.tags` context at
            task runtime.
        version: An optional string specifying the version of this task definition
        cache_policy: A cache policy that determines the level of caching for this task
        cache_key_fn: An optional callable that, given the task run context and call
            parameters, generates a string key; if the key matches a previous completed
            state, that state result will be restored instead of running the task again.
        cache_expiration: An optional amount of time indicating how long cached states
            for this task should be restorable; if not provided, cached states will
            never expire.
        task_run_name: An optional name to distinguish runs of this task; this name can be provided
            as a string template with the task's keyword arguments as variables,
            or a function that returns a string.
        retries: An optional number of times to retry on task run failure.
        retry_delay_seconds: Optionally configures how long to wait before retrying the
            task after failure. This is only applicable if `retries` is nonzero. This
            setting can either be a number of seconds, a list of retry delays, or a
            callable that, given the total number of retries, generates a list of retry
            delays. If a number of seconds, that delay will be applied to all retries.
            If a list, each retry will wait for the corresponding delay before retrying.
            When passing a callable or a list, the number of configured retry delays
            cannot exceed 50.
        retry_jitter_factor: An optional factor that defines the factor to which a retry
            can be jittered in order to avoid a "thundering herd".
        persist_result: A toggle indicating whether the result of this task
            should be persisted to result storage. Defaults to `None`, which
            indicates that the global default should be used (which is `True` by
            default).
        result_storage: An optional block to use to persist the result of this task.
            Defaults to the value set in the flow the task is called in.
        result_storage_key: An optional key to store the result in storage at when persisted.
            Defaults to a unique identifier.
        result_serializer: An optional serializer to use to serialize the result of this
            task for persistence. Defaults to the value set in the flow the task is
            called in.
        timeout_seconds: An optional number of seconds indicating a maximum runtime for
            the task. If the task exceeds this runtime, it will be marked as failed.
        log_prints: If set, `print` statements in the task will be redirected to the
            Prefect logger for the task run. Defaults to `None`, which indicates
            that the value from the flow should be used.
        refresh_cache: If set, cached results for the cache key are not used.
            Defaults to `None`, which indicates that a cached result from a previous
            execution with matching cache key is used.
        on_failure: An optional list of callables to run when the task enters a failed state.
        on_completion: An optional list of callables to run when the task enters a completed state.
        on_commit: An optional list of callables to run when the task's idempotency record is committed.
        on_rollback: An optional list of callables to run when the task rolls back.
        retry_condition_fn: An optional callable run when a task run returns a Failed state. Should
            return `True` if the task should continue to its retry policy (e.g. `retries=3`), and `False` if the task
            should end as failed. Defaults to `None`, indicating the task should always continue
            to its retry policy.
        viz_return_value: An optional value to return when the task dependency tree is visualized.
    """

    # NOTE: These parameters (types, defaults, and docstrings) should be duplicated
    #       exactly in the @task decorator
    def __init__(
        self,
        fn: Callable[P, R],
        name: Optional[str] = None,
        description: Optional[str] = None,
        tags: Optional[Iterable[str]] = None,
        version: Optional[str] = None,
        cache_policy: Optional[CachePolicy] = NotSet,
        cache_key_fn: Optional[
            Callable[["TaskRunContext", Dict[str, Any]], Optional[str]]
        ] = None,
        cache_expiration: Optional[datetime.timedelta] = None,
        task_run_name: Optional[Union[Callable[[], str], str]] = None,
        retries: Optional[int] = None,
        retry_delay_seconds: Optional[
            Union[
                float,
                int,
                List[float],
                Callable[[int], List[float]],
            ]
        ] = None,
        retry_jitter_factor: Optional[float] = None,
        persist_result: Optional[bool] = None,
        result_storage: Optional[ResultStorage] = None,
        result_serializer: Optional[ResultSerializer] = None,
        result_storage_key: Optional[str] = None,
        cache_result_in_memory: bool = True,
        timeout_seconds: Union[int, float, None] = None,
        log_prints: Optional[bool] = False,
        refresh_cache: Optional[bool] = None,
        on_completion: Optional[List[Callable[["Task", TaskRun, State], None]]] = None,
        on_failure: Optional[List[Callable[["Task", TaskRun, State], None]]] = None,
        on_rollback: Optional[List[Callable[["Transaction"], None]]] = None,
        on_commit: Optional[List[Callable[["Transaction"], None]]] = None,
        retry_condition_fn: Optional[Callable[["Task", TaskRun, State], bool]] = None,
        viz_return_value: Optional[Any] = None,
    ):
        # Validate if hook passed is list and contains callables
        hook_categories = [on_completion, on_failure]
        hook_names = ["on_completion", "on_failure"]
        for hooks, hook_name in zip(hook_categories, hook_names):
            if hooks is not None:
                try:
                    hooks = list(hooks)
                except TypeError:
                    raise TypeError(
                        f"Expected iterable for '{hook_name}'; got"
                        f" {type(hooks).__name__} instead. Please provide a list of"
                        f" hooks to '{hook_name}':\n\n"
                        f"@task({hook_name}=[hook1, hook2])\ndef"
                        " my_task():\n\tpass"
                    )

                for hook in hooks:
                    if not callable(hook):
                        raise TypeError(
                            f"Expected callables in '{hook_name}'; got"
                            f" {type(hook).__name__} instead. Please provide a list of"
                            f" hooks to '{hook_name}':\n\n"
                            f"@task({hook_name}=[hook1, hook2])\ndef"
                            " my_task():\n\tpass"
                        )

        if not callable(fn):
            raise TypeError("'fn' must be callable")

        self.description = description or inspect.getdoc(fn)
        update_wrapper(self, fn)
        self.fn = fn

        # the task is considered async if its function is async or an async
        # generator
        self.isasync = inspect.iscoroutinefunction(
            self.fn
        ) or inspect.isasyncgenfunction(self.fn)

        # the task is considered a generator if its function is a generator or
        # an async generator
        self.isgenerator = inspect.isgeneratorfunction(
            self.fn
        ) or inspect.isasyncgenfunction(self.fn)

        if not name:
            if not hasattr(self.fn, "__name__"):
                self.name = type(self.fn).__name__
            else:
                self.name = self.fn.__name__
        else:
            self.name = name

        if task_run_name is not None:
            if not isinstance(task_run_name, str) and not callable(task_run_name):
                raise TypeError(
                    "Expected string or callable for 'task_run_name'; got"
                    f" {type(task_run_name).__name__} instead."
                )
        self.task_run_name = task_run_name

        self.version = version
        self.log_prints = log_prints

        raise_for_reserved_arguments(self.fn, ["return_state", "wait_for"])

        self.tags = set(tags if tags else [])

        if not hasattr(self.fn, "__qualname__"):
            self.task_key = to_qualified_name(type(self.fn))
        else:
            try:
                task_origin_hash = hash_objects(
                    self.name, os.path.abspath(inspect.getsourcefile(self.fn))
                )
            except TypeError:
                task_origin_hash = "unknown-source-file"

            self.task_key = f"{self.fn.__qualname__}-{task_origin_hash}"

        if cache_policy is not NotSet and cache_key_fn is not None:
            logger.warning(
                f"Both `cache_policy` and `cache_key_fn` are set on task {self}. `cache_key_fn` will be used."
            )

        if cache_key_fn:
            cache_policy = CachePolicy.from_cache_key_fn(cache_key_fn)

        # TODO: manage expiration and cache refresh
        self.cache_key_fn = cache_key_fn
        self.cache_expiration = cache_expiration
        self.refresh_cache = refresh_cache

        if persist_result is None:
            persist_result = PREFECT_RESULTS_PERSIST_BY_DEFAULT.value()
        if not persist_result:
            self.cache_policy = None if cache_policy is None else NONE
            if cache_policy and cache_policy is not NotSet and cache_policy != NONE:
                logger.warning(
                    "Ignoring `cache_policy` because `persist_result` is False"
                )
        elif cache_policy is NotSet and result_storage_key is None:
            self.cache_policy = DEFAULT
        elif result_storage_key:
            # TODO: handle this situation with double storage
            self.cache_policy = None
        else:
            self.cache_policy = cache_policy

        # TaskRunPolicy settings
        # TODO: We can instantiate a `TaskRunPolicy` and add Pydantic bound checks to
        #       validate that the user passes positive numbers here

        self.retries = (
            retries if retries is not None else PREFECT_TASK_DEFAULT_RETRIES.value()
        )
        if retry_delay_seconds is None:
            retry_delay_seconds = PREFECT_TASK_DEFAULT_RETRY_DELAY_SECONDS.value()

        if callable(retry_delay_seconds):
            self.retry_delay_seconds = retry_delay_seconds(retries)
        else:
            self.retry_delay_seconds = retry_delay_seconds

        if isinstance(self.retry_delay_seconds, list) and (
            len(self.retry_delay_seconds) > 50
        ):
            raise ValueError("Can not configure more than 50 retry delays per task.")

        if retry_jitter_factor is not None and retry_jitter_factor < 0:
            raise ValueError("`retry_jitter_factor` must be >= 0.")

        self.retry_jitter_factor = retry_jitter_factor
        self.persist_result = persist_result
        self.result_storage = result_storage
        self.result_serializer = result_serializer
        self.result_storage_key = result_storage_key
        self.cache_result_in_memory = cache_result_in_memory
        self.timeout_seconds = float(timeout_seconds) if timeout_seconds else None
        self.on_rollback_hooks = on_rollback or []
        self.on_commit_hooks = on_commit or []
        self.on_completion_hooks = on_completion or []
        self.on_failure_hooks = on_failure or []

        # retry_condition_fn must be a callable or None. If it is neither, raise a TypeError
        if retry_condition_fn is not None and not (callable(retry_condition_fn)):
            raise TypeError(
                "Expected `retry_condition_fn` to be callable, got"
                f" {type(retry_condition_fn).__name__} instead."
            )

        self.retry_condition_fn = retry_condition_fn
        self.viz_return_value = viz_return_value

    @property
    def ismethod(self) -> bool:
        return hasattr(self.fn, "__prefect_self__")

    def __get__(self, instance, owner):
        """
        Implement the descriptor protocol so that the task can be used as an instance method.
        When an instance method is loaded, this method is called with the "self" instance as
        an argument. We return a copy of the task with that instance bound to the task's function.
        """

        # if no instance is provided, it's being accessed on the class
        if instance is None:
            return self

        # if the task is being accessed on an instance, bind the instance to the __prefect_self__ attribute
        # of the task's function. This will allow it to be automatically added to the task's parameters
        else:
            bound_task = copy(self)
            bound_task.fn.__prefect_self__ = instance
            return bound_task

    def with_options(
        self,
        *,
        name: Optional[str] = None,
        description: Optional[str] = None,
        tags: Optional[Iterable[str]] = None,
        cache_policy: Union[CachePolicy, Type[NotSet]] = NotSet,
        cache_key_fn: Optional[
            Callable[["TaskRunContext", Dict[str, Any]], Optional[str]]
        ] = None,
        task_run_name: Optional[Union[Callable[[], str], str]] = None,
        cache_expiration: Optional[datetime.timedelta] = None,
        retries: Union[int, Type[NotSet]] = NotSet,
        retry_delay_seconds: Union[
            float,
            int,
            List[float],
            Callable[[int], List[float]],
            Type[NotSet],
        ] = NotSet,
        retry_jitter_factor: Union[float, Type[NotSet]] = NotSet,
        persist_result: Union[bool, Type[NotSet]] = NotSet,
        result_storage: Union[ResultStorage, Type[NotSet]] = NotSet,
        result_serializer: Union[ResultSerializer, Type[NotSet]] = NotSet,
        result_storage_key: Union[str, Type[NotSet]] = NotSet,
        cache_result_in_memory: Optional[bool] = None,
        timeout_seconds: Union[int, float, None] = None,
        log_prints: Union[bool, Type[NotSet]] = NotSet,
        refresh_cache: Union[bool, Type[NotSet]] = NotSet,
        on_completion: Optional[
            List[Callable[["Task", TaskRun, State], Union[Awaitable[None], None]]]
        ] = None,
        on_failure: Optional[
            List[Callable[["Task", TaskRun, State], Union[Awaitable[None], None]]]
        ] = None,
        retry_condition_fn: Optional[Callable[["Task", TaskRun, State], bool]] = None,
        viz_return_value: Optional[Any] = None,
    ):
        """
        Create a new task from the current object, updating provided options.

        Args:
            name: A new name for the task.
            description: A new description for the task.
            tags: A new set of tags for the task. If given, existing tags are ignored,
                not merged.
            cache_key_fn: A new cache key function for the task.
            cache_expiration: A new cache expiration time for the task.
            task_run_name: An optional name to distinguish runs of this task; this name can be provided
                as a string template with the task's keyword arguments as variables,
                or a function that returns a string.
            retries: A new number of times to retry on task run failure.
            retry_delay_seconds: Optionally configures how long to wait before retrying
                the task after failure. This is only applicable if `retries` is nonzero.
                This setting can either be a number of seconds, a list of retry delays,
                or a callable that, given the total number of retries, generates a list
                of retry delays. If a number of seconds, that delay will be applied to
                all retries. If a list, each retry will wait for the corresponding delay
                before retrying. When passing a callable or a list, the number of
                configured retry delays cannot exceed 50.
            retry_jitter_factor: An optional factor that defines the factor to which a
                retry can be jittered in order to avoid a "thundering herd".
            persist_result: A new option for enabling or disabling result persistence.
            result_storage: A new storage type to use for results.
            result_serializer: A new serializer to use for results.
            result_storage_key: A new key for the persisted result to be stored at.
            timeout_seconds: A new maximum time for the task to complete in seconds.
            log_prints: A new option for enabling or disabling redirection of `print` statements.
            refresh_cache: A new option for enabling or disabling cache refresh.
            on_completion: A new list of callables to run when the task enters a completed state.
            on_failure: A new list of callables to run when the task enters a failed state.
            retry_condition_fn: An optional callable run when a task run returns a Failed state.
                Should return `True` if the task should continue to its retry policy, and `False`
                if the task should end as failed. Defaults to `None`, indicating the task should
                always continue to its retry policy.
            viz_return_value: An optional value to return when the task dependency tree is visualized.

        Returns:
            A new `Task` instance.

        Examples:

            Create a new task from an existing task and update the name

            >>> @task(name="My task")
            >>> def my_task():
            >>>     return 1
            >>>
            >>> new_task = my_task.with_options(name="My new task")

            Create a new task from an existing task and update the retry settings

            >>> from random import randint
            >>>
            >>> @task(retries=1, retry_delay_seconds=5)
            >>> def my_task():
            >>>     x = randint(0, 5)
            >>>     if x >= 3:  # Make a task that fails sometimes
            >>>         raise ValueError("Retry me please!")
            >>>     return x
            >>>
            >>> new_task = my_task.with_options(retries=5, retry_delay_seconds=2)

            Use a task with updated options within a flow

            >>> @task(name="My task")
            >>> def my_task():
            >>>     return 1
            >>>
            >>> @flow
            >>> my_flow():
            >>>     new_task = my_task.with_options(name="My new task")
            >>>     new_task()
        """
        return Task(
            fn=self.fn,
            name=name or self.name,
            description=description or self.description,
            tags=tags or copy(self.tags),
            cache_policy=cache_policy
            if cache_policy is not NotSet
            else self.cache_policy,
            cache_key_fn=cache_key_fn or self.cache_key_fn,
            cache_expiration=cache_expiration or self.cache_expiration,
            task_run_name=task_run_name,
            retries=retries if retries is not NotSet else self.retries,
            retry_delay_seconds=(
                retry_delay_seconds
                if retry_delay_seconds is not NotSet
                else self.retry_delay_seconds
            ),
            retry_jitter_factor=(
                retry_jitter_factor
                if retry_jitter_factor is not NotSet
                else self.retry_jitter_factor
            ),
            persist_result=(
                persist_result if persist_result is not NotSet else self.persist_result
            ),
            result_storage=(
                result_storage if result_storage is not NotSet else self.result_storage
            ),
            result_storage_key=(
                result_storage_key
                if result_storage_key is not NotSet
                else self.result_storage_key
            ),
            result_serializer=(
                result_serializer
                if result_serializer is not NotSet
                else self.result_serializer
            ),
            cache_result_in_memory=(
                cache_result_in_memory
                if cache_result_in_memory is not None
                else self.cache_result_in_memory
            ),
            timeout_seconds=(
                timeout_seconds if timeout_seconds is not None else self.timeout_seconds
            ),
            log_prints=(log_prints if log_prints is not NotSet else self.log_prints),
            refresh_cache=(
                refresh_cache if refresh_cache is not NotSet else self.refresh_cache
            ),
            on_completion=on_completion or self.on_completion_hooks,
            on_failure=on_failure or self.on_failure_hooks,
            retry_condition_fn=retry_condition_fn or self.retry_condition_fn,
            viz_return_value=viz_return_value or self.viz_return_value,
        )

    def on_completion(
        self, fn: Callable[["Task", TaskRun, State], None]
    ) -> Callable[["Task", TaskRun, State], None]:
        self.on_completion_hooks.append(fn)
        return fn

    def on_failure(
        self, fn: Callable[["Task", TaskRun, State], None]
    ) -> Callable[["Task", TaskRun, State], None]:
        self.on_failure_hooks.append(fn)
        return fn

    def on_commit(
        self, fn: Callable[["Transaction"], None]
    ) -> Callable[["Transaction"], None]:
        self.on_commit_hooks.append(fn)
        return fn

    def on_rollback(
        self, fn: Callable[["Transaction"], None]
    ) -> Callable[["Transaction"], None]:
        self.on_rollback_hooks.append(fn)
        return fn

    async def create_run(
        self,
        client: Optional["PrefectClient"] = None,
        id: Optional[UUID] = None,
        parameters: Optional[Dict[str, Any]] = None,
        flow_run_context: Optional[FlowRunContext] = None,
        parent_task_run_context: Optional[TaskRunContext] = None,
        wait_for: Optional[Iterable[PrefectFuture]] = None,
        extra_task_inputs: Optional[Dict[str, Set[TaskRunInput]]] = None,
        deferred: bool = False,
    ) -> TaskRun:
        from prefect.utilities.engine import (
            _dynamic_key_for_task_run,
            collect_task_run_inputs_sync,
        )

        if flow_run_context is None:
            flow_run_context = FlowRunContext.get()
        if parent_task_run_context is None:
            parent_task_run_context = TaskRunContext.get()
        if parameters is None:
            parameters = {}
        if client is None:
            client = get_client()

        async with client:
            if not flow_run_context:
                dynamic_key = f"{self.task_key}-{str(uuid4().hex)}"
                task_run_name = self.name
            else:
                dynamic_key = _dynamic_key_for_task_run(
                    context=flow_run_context, task=self
                )
                task_run_name = f"{self.name}-{dynamic_key}"

            if deferred:
                state = Scheduled()
                state.state_details.deferred = True
            else:
                state = Pending()

            # store parameters for background tasks so that task worker
            # can retrieve them at runtime
            if deferred and (parameters or wait_for):
                parameters_id = uuid4()
                state.state_details.task_parameters_id = parameters_id

                # TODO: Improve use of result storage for parameter storage / reference
                self.persist_result = True

                factory = await ResultFactory.from_autonomous_task(self, client=client)
                context = serialize_context()
                data: Dict[str, Any] = {"context": context}
                if parameters:
                    data["parameters"] = parameters
                if wait_for:
                    data["wait_for"] = wait_for
                await factory.store_parameters(parameters_id, data)

            # collect task inputs
            task_inputs = {
                k: collect_task_run_inputs_sync(v) for k, v in parameters.items()
            }

            # collect all parent dependencies
            if task_parents := _infer_parent_task_runs(
                flow_run_context=flow_run_context,
                task_run_context=parent_task_run_context,
                parameters=parameters,
            ):
                task_inputs["__parents__"] = task_parents

            # check wait for dependencies
            if wait_for:
                task_inputs["wait_for"] = collect_task_run_inputs_sync(wait_for)

            # Join extra task inputs
            for k, extras in (extra_task_inputs or {}).items():
                task_inputs[k] = task_inputs[k].union(extras)

            # create the task run
            task_run = client.create_task_run(
                task=self,
                name=task_run_name,
                flow_run_id=(
                    getattr(flow_run_context.flow_run, "id", None)
                    if flow_run_context and flow_run_context.flow_run
                    else None
                ),
                dynamic_key=str(dynamic_key),
                id=id,
                state=state,
                task_inputs=task_inputs,
                extra_tags=TagsContext.get().current_tags,
            )
            # the new engine uses sync clients but old engines use async clients
            if inspect.isawaitable(task_run):
                task_run = await task_run

            return task_run

    @overload
    def __call__(
        self: "Task[P, NoReturn]",
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> None:
        # `NoReturn` matches if a type can't be inferred for the function which stops a
        # sync function from matching the `Coroutine` overload
        ...

    @overload
    def __call__(
        self: "Task[P, T]",
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> T:
        ...

    @overload
    def __call__(
        self: "Task[P, T]",
        *args: P.args,
        return_state: Literal[True],
        **kwargs: P.kwargs,
    ) -> State[T]:
        ...

    def __call__(
        self,
        *args: P.args,
        return_state: bool = False,
        wait_for: Optional[Iterable[PrefectFuture]] = None,
        **kwargs: P.kwargs,
    ):
        """
        Run the task and return the result. If `return_state` is True returns
        the result is wrapped in a Prefect State which provides error handling.
        """
        from prefect.utilities.visualization import (
            get_task_viz_tracker,
            track_viz_task,
        )

        # Convert the call args/kwargs to a parameter dict
        parameters = get_call_parameters(self.fn, args, kwargs)

        return_type = "state" if return_state else "result"

        task_run_tracker = get_task_viz_tracker()
        if task_run_tracker:
            return track_viz_task(
                self.isasync, self.name, parameters, self.viz_return_value
            )

        from prefect.task_engine import run_task

        return run_task(
            task=self,
            parameters=parameters,
            wait_for=wait_for,
            return_type=return_type,
        )

    @overload
    def submit(
        self: "Task[P, NoReturn]",
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> PrefectFuture[NoReturn]:
        # `NoReturn` matches if a type can't be inferred for the function which stops a
        # sync function from matching the `Coroutine` overload
        ...

    @overload
    def submit(
        self: "Task[P, Coroutine[Any, Any, T]]",
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> PrefectFuture[T]:
        ...

    @overload
    def submit(
        self: "Task[P, T]",
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> PrefectFuture[T]:
        ...

    @overload
    def submit(
        self: "Task[P, Coroutine[Any, Any, T]]",
        *args: P.args,
        return_state: Literal[True],
        **kwargs: P.kwargs,
    ) -> State[T]:
        ...

    @overload
    def submit(
        self: "Task[P, T]",
        *args: P.args,
        return_state: Literal[True],
        **kwargs: P.kwargs,
    ) -> State[T]:
        ...

    @deprecated_async_method
    def submit(
        self,
        *args: Any,
        return_state: bool = False,
        wait_for: Optional[Iterable[PrefectFuture]] = None,
        **kwargs: Any,
    ):
        """
        Submit a run of the task to the engine.

        Will create a new task run in the backing API and submit the task to the flow's
        task runner. This call only blocks execution while the task is being submitted,
        once it is submitted, the flow function will continue executing.

        Args:
            *args: Arguments to run the task with
            return_state: Return the result of the flow run wrapped in a
                Prefect State.
            wait_for: Upstream task futures to wait for before starting the task
            **kwargs: Keyword arguments to run the task with

        Returns:
            If `return_state` is False a future allowing asynchronous access to
                the state of the task
            If `return_state` is True a future wrapped in a Prefect State allowing asynchronous access to
                the state of the task

        Examples:

            Define a task

            >>> from prefect import task
            >>> @task
            >>> def my_task():
            >>>     return "hello"

            Run a task in a flow

            >>> from prefect import flow
            >>> @flow
            >>> def my_flow():
            >>>     my_task.submit()

            Wait for a task to finish

            >>> @flow
            >>> def my_flow():
            >>>     my_task.submit().wait()

            Use the result from a task in a flow

            >>> @flow
            >>> def my_flow():
            >>>     print(my_task.submit().result())
            >>>
            >>> my_flow()
            hello

            Run an async task in an async flow

            >>> @task
            >>> async def my_async_task():
            >>>     pass
            >>>
            >>> @flow
            >>> async def my_flow():
            >>>     await my_async_task.submit()

            Run a sync task in an async flow

            >>> @flow
            >>> async def my_flow():
            >>>     my_task.submit()

            Enforce ordering between tasks that do not exchange data
            >>> @task
            >>> def task_1():
            >>>     pass
            >>>
            >>> @task
            >>> def task_2():
            >>>     pass
            >>>
            >>> @flow
            >>> def my_flow():
            >>>     x = task_1.submit()
            >>>
            >>>     # task 2 will wait for task_1 to complete
            >>>     y = task_2.submit(wait_for=[x])

        """

        from prefect.utilities.visualization import (
            VisualizationUnsupportedError,
            get_task_viz_tracker,
        )

        # Convert the call args/kwargs to a parameter dict
        parameters = get_call_parameters(self.fn, args, kwargs)
        flow_run_context = FlowRunContext.get()

        if not flow_run_context:
            raise RuntimeError(
                "Unable to determine task runner to use for submission. If you are"
                " submitting a task outside of a flow, please use `.delay`"
                " to submit the task run for deferred execution."
            )

        task_viz_tracker = get_task_viz_tracker()
        if task_viz_tracker:
            raise VisualizationUnsupportedError(
                "`task.submit()` is not currently supported by `flow.visualize()`"
            )

        task_runner = flow_run_context.task_runner
        future = task_runner.submit(self, parameters, wait_for)
        if return_state:
            future.wait()
            return future.state
        else:
            return future

    @overload
    def map(
        self: "Task[P, NoReturn]",
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> PrefectFutureList[PrefectFuture[NoReturn]]:
        ...

    @overload
    def map(
        self: "Task[P, Coroutine[Any, Any, T]]",
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> PrefectFutureList[PrefectFuture[T]]:
        ...

    @overload
    def map(
        self: "Task[P, T]",
        *args: P.args,
        **kwargs: P.kwargs,
    ) -> PrefectFutureList[PrefectFuture[T]]:
        ...

    @overload
    def map(
        self: "Task[P, Coroutine[Any, Any, T]]",
        *args: P.args,
        return_state: Literal[True],
        **kwargs: P.kwargs,
    ) -> PrefectFutureList[State[T]]:
        ...

    @overload
    def map(
        self: "Task[P, T]",
        *args: P.args,
        return_state: Literal[True],
        **kwargs: P.kwargs,
    ) -> PrefectFutureList[State[T]]:
        ...

    @deprecated_async_method
    def map(
        self,
        *args: Any,
        return_state: bool = False,
        wait_for: Optional[Iterable[PrefectFuture]] = None,
        deferred: bool = False,
        **kwargs: Any,
    ):
        """
        Submit a mapped run of the task to a worker.

        Must be called within a flow run context. Will return a list of futures
        that should be waited on before exiting the flow context to ensure all
        mapped tasks have completed.

        Must be called with at least one iterable and all iterables must be
        the same length. Any arguments that are not iterable will be treated as
        a static value and each task run will receive the same value.

        Will create as many task runs as the length of the iterable(s) in the
        backing API and submit the task runs to the flow's task runner. This
        call blocks if given a future as input while the future is resolved. It
        also blocks while the tasks are being submitted, once they are
        submitted, the flow function will continue executing.

        Args:
            *args: Iterable and static arguments to run the tasks with
            return_state: Return a list of Prefect States that wrap the results
                of each task run.
            wait_for: Upstream task futures to wait for before starting the
                task
            **kwargs: Keyword iterable arguments to run the task with

        Returns:
            A list of futures allowing asynchronous access to the state of the
            tasks

        Examples:

            Define a task

            >>> from prefect import task
            >>> @task
            >>> def my_task(x):
            >>>     return x + 1

            Create mapped tasks

            >>> from prefect import flow
            >>> @flow
            >>> def my_flow():
            >>>     return my_task.map([1, 2, 3])

            Wait for all mapped tasks to finish

            >>> @flow
            >>> def my_flow():
            >>>     futures = my_task.map([1, 2, 3])
            >>>     futures.wait():
            >>>     # Now all of the mapped tasks have finished
            >>>     my_task(10)

            Use the result from mapped tasks in a flow

            >>> @flow
            >>> def my_flow():
            >>>     futures = my_task.map([1, 2, 3])
            >>>     for x in futures.result():
            >>>         print(x)
            >>> my_flow()
            2
            3
            4

            Enforce ordering between tasks that do not exchange data
            >>> @task
            >>> def task_1(x):
            >>>     pass
            >>>
            >>> @task
            >>> def task_2(y):
            >>>     pass
            >>>
            >>> @flow
            >>> def my_flow():
            >>>     x = task_1.submit()
            >>>
            >>>     # task 2 will wait for task_1 to complete
            >>>     y = task_2.map([1, 2, 3], wait_for=[x])
            >>>     return y

            Use a non-iterable input as a constant across mapped tasks
            >>> @task
            >>> def display(prefix, item):
            >>>    print(prefix, item)
            >>>
            >>> @flow
            >>> def my_flow():
            >>>     return display.map("Check it out: ", [1, 2, 3])
            >>>
            >>> my_flow()
            Check it out: 1
            Check it out: 2
            Check it out: 3

            Use `unmapped` to treat an iterable argument as a constant
            >>> from prefect import unmapped
            >>>
            >>> @task
            >>> def add_n_to_items(items, n):
            >>>     return [item + n for item in items]
            >>>
            >>> @flow
            >>> def my_flow():
            >>>     return add_n_to_items.map(unmapped([10, 20]), n=[1, 2, 3])
            >>>
            >>> my_flow()
            [[11, 21], [12, 22], [13, 23]]
        """

        from prefect.task_runners import TaskRunner
        from prefect.utilities.visualization import (
            VisualizationUnsupportedError,
            get_task_viz_tracker,
        )

        # Convert the call args/kwargs to a parameter dict; do not apply defaults
        # since they should not be mapped over
        parameters = get_call_parameters(self.fn, args, kwargs, apply_defaults=False)
        flow_run_context = FlowRunContext.get()

        task_viz_tracker = get_task_viz_tracker()
        if task_viz_tracker:
            raise VisualizationUnsupportedError(
                "`task.map()` is not currently supported by `flow.visualize()`"
            )

        if deferred:
            parameters_list = expand_mapping_parameters(self.fn, parameters)
            futures = [
                self.apply_async(kwargs=parameters, wait_for=wait_for)
                for parameters in parameters_list
            ]
        elif task_runner := getattr(flow_run_context, "task_runner", None):
            assert isinstance(task_runner, TaskRunner)
            futures = task_runner.map(self, parameters, wait_for)
        else:
            raise RuntimeError(
                "Unable to determine task runner to use for mapped task runs. If"
                " you are mapping a task outside of a flow, please provide"
                " `deferred=True` to submit the mapped task runs for deferred"
                " execution."
            )
        if return_state:
            states = []
            for future in futures:
                future.wait()
                states.append(future.state)
            return states
        else:
            return futures

    def apply_async(
        self,
        args: Optional[Tuple[Any, ...]] = None,
        kwargs: Optional[Dict[str, Any]] = None,
        wait_for: Optional[Iterable[PrefectFuture]] = None,
        dependencies: Optional[Dict[str, Set[TaskRunInput]]] = None,
    ) -> PrefectDistributedFuture:
        """
        Create a pending task run for a task worker to execute.

        Args:
            args: Arguments to run the task with
            kwargs: Keyword arguments to run the task with

        Returns:
            A PrefectDistributedFuture object representing the pending task run

        Examples:

            Define a task

            >>> from prefect import task
            >>> @task
            >>> def my_task(name: str = "world"):
            >>>     return f"hello {name}"

            Create a pending task run for the task

            >>> from prefect import flow
            >>> @flow
            >>> def my_flow():
            >>>     my_task.apply_async(("marvin",))

            Wait for a task to finish

            >>> @flow
            >>> def my_flow():
            >>>     my_task.apply_async(("marvin",)).wait()


            >>> @flow
            >>> def my_flow():
            >>>     print(my_task.apply_async(("marvin",)).result())
            >>>
            >>> my_flow()
            hello marvin

            TODO: Enforce ordering between tasks that do not exchange data
            >>> @task
            >>> def task_1():
            >>>     pass
            >>>
            >>> @task
            >>> def task_2():
            >>>     pass
            >>>
            >>> @flow
            >>> def my_flow():
            >>>     x = task_1.apply_async()
            >>>
            >>>     # task 2 will wait for task_1 to complete
            >>>     y = task_2.apply_async(wait_for=[x])

        """
        from prefect.utilities.visualization import (
            VisualizationUnsupportedError,
            get_task_viz_tracker,
        )

        task_viz_tracker = get_task_viz_tracker()
        if task_viz_tracker:
            raise VisualizationUnsupportedError(
                "`task.apply_async()` is not currently supported by `flow.visualize()`"
            )
        args = args or ()
        kwargs = kwargs or {}

        # Convert the call args/kwargs to a parameter dict
        parameters = get_call_parameters(self.fn, args, kwargs)

        task_run = run_coro_as_sync(
            self.create_run(
                parameters=parameters,
                deferred=True,
                wait_for=wait_for,
                extra_task_inputs=dependencies,
            )
        )
        return PrefectDistributedFuture(task_run_id=task_run.id)

    def delay(self, *args: P.args, **kwargs: P.kwargs) -> PrefectDistributedFuture:
        """
        An alias for `apply_async` with simpler calling semantics.

        Avoids having to use explicit "args" and "kwargs" arguments. Arguments
        will pass through as-is to the task.

        Examples:

                Define a task

                >>> from prefect import task
                >>> @task
                >>> def my_task(name: str = "world"):
                >>>     return f"hello {name}"

                Create a pending task run for the task

                >>> from prefect import flow
                >>> @flow
                >>> def my_flow():
                >>>     my_task.delay("marvin")

                Wait for a task to finish

                >>> @flow
                >>> def my_flow():
                >>>     my_task.delay("marvin").wait()

                Use the result from a task in a flow

                >>> @flow
                >>> def my_flow():
                >>>     print(my_task.delay("marvin").result())
                >>>
                >>> my_flow()
                hello marvin
        """
        return self.apply_async(args=args, kwargs=kwargs)

    @sync_compatible
    async def serve(self) -> NoReturn:
        """Serve the task using the provided task runner. This method is used to
        establish a websocket connection with the Prefect server and listen for
        submitted task runs to execute.

        Args:
            task_runner: The task runner to use for serving the task. If not provided,
                the default ConcurrentTaskRunner will be used.

        Examples:
            Serve a task using the default task runner
            >>> @task
            >>> def my_task():
            >>>     return 1

            >>> my_task.serve()
        """
        from prefect.task_worker import serve

        await serve(self)

__call__(*args, return_state=False, wait_for=None, **kwargs)

Run the task and return the result. If return_state is True returns the result is wrapped in a Prefect State which provides error handling.

Source code in src/prefect/tasks.py
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
def __call__(
    self,
    *args: P.args,
    return_state: bool = False,
    wait_for: Optional[Iterable[PrefectFuture]] = None,
    **kwargs: P.kwargs,
):
    """
    Run the task and return the result. If `return_state` is True returns
    the result is wrapped in a Prefect State which provides error handling.
    """
    from prefect.utilities.visualization import (
        get_task_viz_tracker,
        track_viz_task,
    )

    # Convert the call args/kwargs to a parameter dict
    parameters = get_call_parameters(self.fn, args, kwargs)

    return_type = "state" if return_state else "result"

    task_run_tracker = get_task_viz_tracker()
    if task_run_tracker:
        return track_viz_task(
            self.isasync, self.name, parameters, self.viz_return_value
        )

    from prefect.task_engine import run_task

    return run_task(
        task=self,
        parameters=parameters,
        wait_for=wait_for,
        return_type=return_type,
    )

__get__(instance, owner)

Implement the descriptor protocol so that the task can be used as an instance method. When an instance method is loaded, this method is called with the "self" instance as an argument. We return a copy of the task with that instance bound to the task's function.

Source code in src/prefect/tasks.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
def __get__(self, instance, owner):
    """
    Implement the descriptor protocol so that the task can be used as an instance method.
    When an instance method is loaded, this method is called with the "self" instance as
    an argument. We return a copy of the task with that instance bound to the task's function.
    """

    # if no instance is provided, it's being accessed on the class
    if instance is None:
        return self

    # if the task is being accessed on an instance, bind the instance to the __prefect_self__ attribute
    # of the task's function. This will allow it to be automatically added to the task's parameters
    else:
        bound_task = copy(self)
        bound_task.fn.__prefect_self__ = instance
        return bound_task

apply_async(args=None, kwargs=None, wait_for=None, dependencies=None)

Create a pending task run for a task worker to execute.

Parameters:

Name Type Description Default
args Optional[Tuple[Any, ...]]

Arguments to run the task with

None
kwargs Optional[Dict[str, Any]]

Keyword arguments to run the task with

None

Returns:

Type Description
PrefectDistributedFuture

A PrefectDistributedFuture object representing the pending task run

Define a task

>>> from prefect import task
>>> @task
>>> def my_task(name: str = "world"):
>>>     return f"hello {name}"

Create a pending task run for the task

>>> from prefect import flow
>>> @flow
>>> def my_flow():
>>>     my_task.apply_async(("marvin",))

Wait for a task to finish

>>> @flow
>>> def my_flow():
>>>     my_task.apply_async(("marvin",)).wait()


>>> @flow
>>> def my_flow():
>>>     print(my_task.apply_async(("marvin",)).result())
>>>
>>> my_flow()
hello marvin

TODO: Enforce ordering between tasks that do not exchange data
>>> @task
>>> def task_1():
>>>     pass
>>>
>>> @task
>>> def task_2():
>>>     pass
>>>
>>> @flow
>>> def my_flow():
>>>     x = task_1.apply_async()
>>>
>>>     # task 2 will wait for task_1 to complete
>>>     y = task_2.apply_async(wait_for=[x])
Source code in src/prefect/tasks.py
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
def apply_async(
    self,
    args: Optional[Tuple[Any, ...]] = None,
    kwargs: Optional[Dict[str, Any]] = None,
    wait_for: Optional[Iterable[PrefectFuture]] = None,
    dependencies: Optional[Dict[str, Set[TaskRunInput]]] = None,
) -> PrefectDistributedFuture:
    """
    Create a pending task run for a task worker to execute.

    Args:
        args: Arguments to run the task with
        kwargs: Keyword arguments to run the task with

    Returns:
        A PrefectDistributedFuture object representing the pending task run

    Examples:

        Define a task

        >>> from prefect import task
        >>> @task
        >>> def my_task(name: str = "world"):
        >>>     return f"hello {name}"

        Create a pending task run for the task

        >>> from prefect import flow
        >>> @flow
        >>> def my_flow():
        >>>     my_task.apply_async(("marvin",))

        Wait for a task to finish

        >>> @flow
        >>> def my_flow():
        >>>     my_task.apply_async(("marvin",)).wait()


        >>> @flow
        >>> def my_flow():
        >>>     print(my_task.apply_async(("marvin",)).result())
        >>>
        >>> my_flow()
        hello marvin

        TODO: Enforce ordering between tasks that do not exchange data
        >>> @task
        >>> def task_1():
        >>>     pass
        >>>
        >>> @task
        >>> def task_2():
        >>>     pass
        >>>
        >>> @flow
        >>> def my_flow():
        >>>     x = task_1.apply_async()
        >>>
        >>>     # task 2 will wait for task_1 to complete
        >>>     y = task_2.apply_async(wait_for=[x])

    """
    from prefect.utilities.visualization import (
        VisualizationUnsupportedError,
        get_task_viz_tracker,
    )

    task_viz_tracker = get_task_viz_tracker()
    if task_viz_tracker:
        raise VisualizationUnsupportedError(
            "`task.apply_async()` is not currently supported by `flow.visualize()`"
        )
    args = args or ()
    kwargs = kwargs or {}

    # Convert the call args/kwargs to a parameter dict
    parameters = get_call_parameters(self.fn, args, kwargs)

    task_run = run_coro_as_sync(
        self.create_run(
            parameters=parameters,
            deferred=True,
            wait_for=wait_for,
            extra_task_inputs=dependencies,
        )
    )
    return PrefectDistributedFuture(task_run_id=task_run.id)

delay(*args, **kwargs)

An alias for apply_async with simpler calling semantics.

Avoids having to use explicit "args" and "kwargs" arguments. Arguments will pass through as-is to the task.

Examples:

    Define a task

    >>> from prefect import task
    >>> @task
    >>> def my_task(name: str = "world"):
    >>>     return f"hello {name}"

    Create a pending task run for the task

    >>> from prefect import flow
    >>> @flow
    >>> def my_flow():
    >>>     my_task.delay("marvin")

    Wait for a task to finish

    >>> @flow
    >>> def my_flow():
    >>>     my_task.delay("marvin").wait()

    Use the result from a task in a flow

    >>> @flow
    >>> def my_flow():
    >>>     print(my_task.delay("marvin").result())
    >>>
    >>> my_flow()
    hello marvin
Source code in src/prefect/tasks.py
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
def delay(self, *args: P.args, **kwargs: P.kwargs) -> PrefectDistributedFuture:
    """
    An alias for `apply_async` with simpler calling semantics.

    Avoids having to use explicit "args" and "kwargs" arguments. Arguments
    will pass through as-is to the task.

    Examples:

            Define a task

            >>> from prefect import task
            >>> @task
            >>> def my_task(name: str = "world"):
            >>>     return f"hello {name}"

            Create a pending task run for the task

            >>> from prefect import flow
            >>> @flow
            >>> def my_flow():
            >>>     my_task.delay("marvin")

            Wait for a task to finish

            >>> @flow
            >>> def my_flow():
            >>>     my_task.delay("marvin").wait()

            Use the result from a task in a flow

            >>> @flow
            >>> def my_flow():
            >>>     print(my_task.delay("marvin").result())
            >>>
            >>> my_flow()
            hello marvin
    """
    return self.apply_async(args=args, kwargs=kwargs)

map(*args, return_state=False, wait_for=None, deferred=False, **kwargs)

Submit a mapped run of the task to a worker.

Must be called within a flow run context. Will return a list of futures that should be waited on before exiting the flow context to ensure all mapped tasks have completed.

Must be called with at least one iterable and all iterables must be the same length. Any arguments that are not iterable will be treated as a static value and each task run will receive the same value.

Will create as many task runs as the length of the iterable(s) in the backing API and submit the task runs to the flow's task runner. This call blocks if given a future as input while the future is resolved. It also blocks while the tasks are being submitted, once they are submitted, the flow function will continue executing.

Parameters:

Name Type Description Default
*args Any

Iterable and static arguments to run the tasks with

()
return_state bool

Return a list of Prefect States that wrap the results of each task run.

False
wait_for Optional[Iterable[PrefectFuture]]

Upstream task futures to wait for before starting the task

None
**kwargs Any

Keyword iterable arguments to run the task with

{}

Returns:

Type Description

A list of futures allowing asynchronous access to the state of the

tasks

Define a task

>>> from prefect import task
>>> @task
>>> def my_task(x):
>>>     return x + 1

Create mapped tasks

>>> from prefect import flow
>>> @flow
>>> def my_flow():
>>>     return my_task.map([1, 2, 3])

Wait for all mapped tasks to finish

>>> @flow
>>> def my_flow():
>>>     futures = my_task.map([1, 2, 3])
>>>     futures.wait():
>>>     # Now all of the mapped tasks have finished
>>>     my_task(10)

Use the result from mapped tasks in a flow

>>> @flow
>>> def my_flow():
>>>     futures = my_task.map([1, 2, 3])
>>>     for x in futures.result():
>>>         print(x)
>>> my_flow()
2
3
4

Enforce ordering between tasks that do not exchange data
>>> @task
>>> def task_1(x):
>>>     pass
>>>
>>> @task
>>> def task_2(y):
>>>     pass
>>>
>>> @flow
>>> def my_flow():
>>>     x = task_1.submit()
>>>
>>>     # task 2 will wait for task_1 to complete
>>>     y = task_2.map([1, 2, 3], wait_for=[x])
>>>     return y

Use a non-iterable input as a constant across mapped tasks
>>> @task
>>> def display(prefix, item):
>>>    print(prefix, item)
>>>
>>> @flow
>>> def my_flow():
>>>     return display.map("Check it out: ", [1, 2, 3])
>>>
>>> my_flow()
Check it out: 1
Check it out: 2
Check it out: 3

Use `unmapped` to treat an iterable argument as a constant
>>> from prefect import unmapped
>>>
>>> @task
>>> def add_n_to_items(items, n):
>>>     return [item + n for item in items]
>>>
>>> @flow
>>> def my_flow():
>>>     return add_n_to_items.map(unmapped([10, 20]), n=[1, 2, 3])
>>>
>>> my_flow()
[[11, 21], [12, 22], [13, 23]]
Source code in src/prefect/tasks.py
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
@deprecated_async_method
def map(
    self,
    *args: Any,
    return_state: bool = False,
    wait_for: Optional[Iterable[PrefectFuture]] = None,
    deferred: bool = False,
    **kwargs: Any,
):
    """
    Submit a mapped run of the task to a worker.

    Must be called within a flow run context. Will return a list of futures
    that should be waited on before exiting the flow context to ensure all
    mapped tasks have completed.

    Must be called with at least one iterable and all iterables must be
    the same length. Any arguments that are not iterable will be treated as
    a static value and each task run will receive the same value.

    Will create as many task runs as the length of the iterable(s) in the
    backing API and submit the task runs to the flow's task runner. This
    call blocks if given a future as input while the future is resolved. It
    also blocks while the tasks are being submitted, once they are
    submitted, the flow function will continue executing.

    Args:
        *args: Iterable and static arguments to run the tasks with
        return_state: Return a list of Prefect States that wrap the results
            of each task run.
        wait_for: Upstream task futures to wait for before starting the
            task
        **kwargs: Keyword iterable arguments to run the task with

    Returns:
        A list of futures allowing asynchronous access to the state of the
        tasks

    Examples:

        Define a task

        >>> from prefect import task
        >>> @task
        >>> def my_task(x):
        >>>     return x + 1

        Create mapped tasks

        >>> from prefect import flow
        >>> @flow
        >>> def my_flow():
        >>>     return my_task.map([1, 2, 3])

        Wait for all mapped tasks to finish

        >>> @flow
        >>> def my_flow():
        >>>     futures = my_task.map([1, 2, 3])
        >>>     futures.wait():
        >>>     # Now all of the mapped tasks have finished
        >>>     my_task(10)

        Use the result from mapped tasks in a flow

        >>> @flow
        >>> def my_flow():
        >>>     futures = my_task.map([1, 2, 3])
        >>>     for x in futures.result():
        >>>         print(x)
        >>> my_flow()
        2
        3
        4

        Enforce ordering between tasks that do not exchange data
        >>> @task
        >>> def task_1(x):
        >>>     pass
        >>>
        >>> @task
        >>> def task_2(y):
        >>>     pass
        >>>
        >>> @flow
        >>> def my_flow():
        >>>     x = task_1.submit()
        >>>
        >>>     # task 2 will wait for task_1 to complete
        >>>     y = task_2.map([1, 2, 3], wait_for=[x])
        >>>     return y

        Use a non-iterable input as a constant across mapped tasks
        >>> @task
        >>> def display(prefix, item):
        >>>    print(prefix, item)
        >>>
        >>> @flow
        >>> def my_flow():
        >>>     return display.map("Check it out: ", [1, 2, 3])
        >>>
        >>> my_flow()
        Check it out: 1
        Check it out: 2
        Check it out: 3

        Use `unmapped` to treat an iterable argument as a constant
        >>> from prefect import unmapped
        >>>
        >>> @task
        >>> def add_n_to_items(items, n):
        >>>     return [item + n for item in items]
        >>>
        >>> @flow
        >>> def my_flow():
        >>>     return add_n_to_items.map(unmapped([10, 20]), n=[1, 2, 3])
        >>>
        >>> my_flow()
        [[11, 21], [12, 22], [13, 23]]
    """

    from prefect.task_runners import TaskRunner
    from prefect.utilities.visualization import (
        VisualizationUnsupportedError,
        get_task_viz_tracker,
    )

    # Convert the call args/kwargs to a parameter dict; do not apply defaults
    # since they should not be mapped over
    parameters = get_call_parameters(self.fn, args, kwargs, apply_defaults=False)
    flow_run_context = FlowRunContext.get()

    task_viz_tracker = get_task_viz_tracker()
    if task_viz_tracker:
        raise VisualizationUnsupportedError(
            "`task.map()` is not currently supported by `flow.visualize()`"
        )

    if deferred:
        parameters_list = expand_mapping_parameters(self.fn, parameters)
        futures = [
            self.apply_async(kwargs=parameters, wait_for=wait_for)
            for parameters in parameters_list
        ]
    elif task_runner := getattr(flow_run_context, "task_runner", None):
        assert isinstance(task_runner, TaskRunner)
        futures = task_runner.map(self, parameters, wait_for)
    else:
        raise RuntimeError(
            "Unable to determine task runner to use for mapped task runs. If"
            " you are mapping a task outside of a flow, please provide"
            " `deferred=True` to submit the mapped task runs for deferred"
            " execution."
        )
    if return_state:
        states = []
        for future in futures:
            future.wait()
            states.append(future.state)
        return states
    else:
        return futures

serve() async

Serve the task using the provided task runner. This method is used to establish a websocket connection with the Prefect server and listen for submitted task runs to execute.

Parameters:

Name Type Description Default
task_runner

The task runner to use for serving the task. If not provided, the default ConcurrentTaskRunner will be used.

required

Examples:

Serve a task using the default task runner

>>> @task
>>> def my_task():
>>>     return 1
>>> my_task.serve()
Source code in src/prefect/tasks.py
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
@sync_compatible
async def serve(self) -> NoReturn:
    """Serve the task using the provided task runner. This method is used to
    establish a websocket connection with the Prefect server and listen for
    submitted task runs to execute.

    Args:
        task_runner: The task runner to use for serving the task. If not provided,
            the default ConcurrentTaskRunner will be used.

    Examples:
        Serve a task using the default task runner
        >>> @task
        >>> def my_task():
        >>>     return 1

        >>> my_task.serve()
    """
    from prefect.task_worker import serve

    await serve(self)

submit(*args, return_state=False, wait_for=None, **kwargs)

Submit a run of the task to the engine.

Will create a new task run in the backing API and submit the task to the flow's task runner. This call only blocks execution while the task is being submitted, once it is submitted, the flow function will continue executing.

Parameters:

Name Type Description Default
*args Any

Arguments to run the task with

()
return_state bool

Return the result of the flow run wrapped in a Prefect State.

False
wait_for Optional[Iterable[PrefectFuture]]

Upstream task futures to wait for before starting the task

None
**kwargs Any

Keyword arguments to run the task with

{}

Returns:

Type Description

If return_state is False a future allowing asynchronous access to the state of the task

If return_state is True a future wrapped in a Prefect State allowing asynchronous access to the state of the task

Define a task

>>> from prefect import task
>>> @task
>>> def my_task():
>>>     return "hello"

Run a task in a flow

>>> from prefect import flow
>>> @flow
>>> def my_flow():
>>>     my_task.submit()

Wait for a task to finish

>>> @flow
>>> def my_flow():
>>>     my_task.submit().wait()

Use the result from a task in a flow

>>> @flow
>>> def my_flow():
>>>     print(my_task.submit().result())
>>>
>>> my_flow()
hello

Run an async task in an async flow

>>> @task
>>> async def my_async_task():
>>>     pass
>>>
>>> @flow
>>> async def my_flow():
>>>     await my_async_task.submit()

Run a sync task in an async flow

>>> @flow
>>> async def my_flow():
>>>     my_task.submit()

Enforce ordering between tasks that do not exchange data
>>> @task
>>> def task_1():
>>>     pass
>>>
>>> @task
>>> def task_2():
>>>     pass
>>>
>>> @flow
>>> def my_flow():
>>>     x = task_1.submit()
>>>
>>>     # task 2 will wait for task_1 to complete
>>>     y = task_2.submit(wait_for=[x])
Source code in src/prefect/tasks.py
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
@deprecated_async_method
def submit(
    self,
    *args: Any,
    return_state: bool = False,
    wait_for: Optional[Iterable[PrefectFuture]] = None,
    **kwargs: Any,
):
    """
    Submit a run of the task to the engine.

    Will create a new task run in the backing API and submit the task to the flow's
    task runner. This call only blocks execution while the task is being submitted,
    once it is submitted, the flow function will continue executing.

    Args:
        *args: Arguments to run the task with
        return_state: Return the result of the flow run wrapped in a
            Prefect State.
        wait_for: Upstream task futures to wait for before starting the task
        **kwargs: Keyword arguments to run the task with

    Returns:
        If `return_state` is False a future allowing asynchronous access to
            the state of the task
        If `return_state` is True a future wrapped in a Prefect State allowing asynchronous access to
            the state of the task

    Examples:

        Define a task

        >>> from prefect import task
        >>> @task
        >>> def my_task():
        >>>     return "hello"

        Run a task in a flow

        >>> from prefect import flow
        >>> @flow
        >>> def my_flow():
        >>>     my_task.submit()

        Wait for a task to finish

        >>> @flow
        >>> def my_flow():
        >>>     my_task.submit().wait()

        Use the result from a task in a flow

        >>> @flow
        >>> def my_flow():
        >>>     print(my_task.submit().result())
        >>>
        >>> my_flow()
        hello

        Run an async task in an async flow

        >>> @task
        >>> async def my_async_task():
        >>>     pass
        >>>
        >>> @flow
        >>> async def my_flow():
        >>>     await my_async_task.submit()

        Run a sync task in an async flow

        >>> @flow
        >>> async def my_flow():
        >>>     my_task.submit()

        Enforce ordering between tasks that do not exchange data
        >>> @task
        >>> def task_1():
        >>>     pass
        >>>
        >>> @task
        >>> def task_2():
        >>>     pass
        >>>
        >>> @flow
        >>> def my_flow():
        >>>     x = task_1.submit()
        >>>
        >>>     # task 2 will wait for task_1 to complete
        >>>     y = task_2.submit(wait_for=[x])

    """

    from prefect.utilities.visualization import (
        VisualizationUnsupportedError,
        get_task_viz_tracker,
    )

    # Convert the call args/kwargs to a parameter dict
    parameters = get_call_parameters(self.fn, args, kwargs)
    flow_run_context = FlowRunContext.get()

    if not flow_run_context:
        raise RuntimeError(
            "Unable to determine task runner to use for submission. If you are"
            " submitting a task outside of a flow, please use `.delay`"
            " to submit the task run for deferred execution."
        )

    task_viz_tracker = get_task_viz_tracker()
    if task_viz_tracker:
        raise VisualizationUnsupportedError(
            "`task.submit()` is not currently supported by `flow.visualize()`"
        )

    task_runner = flow_run_context.task_runner
    future = task_runner.submit(self, parameters, wait_for)
    if return_state:
        future.wait()
        return future.state
    else:
        return future

with_options(*, name=None, description=None, tags=None, cache_policy=NotSet, cache_key_fn=None, task_run_name=None, cache_expiration=None, retries=NotSet, retry_delay_seconds=NotSet, retry_jitter_factor=NotSet, persist_result=NotSet, result_storage=NotSet, result_serializer=NotSet, result_storage_key=NotSet, cache_result_in_memory=None, timeout_seconds=None, log_prints=NotSet, refresh_cache=NotSet, on_completion=None, on_failure=None, retry_condition_fn=None, viz_return_value=None)

Create a new task from the current object, updating provided options.

Parameters:

Name Type Description Default
name Optional[str]

A new name for the task.

None
description Optional[str]

A new description for the task.

None
tags Optional[Iterable[str]]

A new set of tags for the task. If given, existing tags are ignored, not merged.

None
cache_key_fn Optional[Callable[[TaskRunContext, Dict[str, Any]], Optional[str]]]

A new cache key function for the task.

None
cache_expiration Optional[timedelta]

A new cache expiration time for the task.

None
task_run_name Optional[Union[Callable[[], str], str]]

An optional name to distinguish runs of this task; this name can be provided as a string template with the task's keyword arguments as variables, or a function that returns a string.

None
retries Union[int, Type[NotSet]]

A new number of times to retry on task run failure.

NotSet
retry_delay_seconds Union[float, int, List[float], Callable[[int], List[float]], Type[NotSet]]

Optionally configures how long to wait before retrying the task after failure. This is only applicable if retries is nonzero. This setting can either be a number of seconds, a list of retry delays, or a callable that, given the total number of retries, generates a list of retry delays. If a number of seconds, that delay will be applied to all retries. If a list, each retry will wait for the corresponding delay before retrying. When passing a callable or a list, the number of configured retry delays cannot exceed 50.

NotSet
retry_jitter_factor Union[float, Type[NotSet]]

An optional factor that defines the factor to which a retry can be jittered in order to avoid a "thundering herd".

NotSet
persist_result Union[bool, Type[NotSet]]

A new option for enabling or disabling result persistence.

NotSet
result_storage Union[ResultStorage, Type[NotSet]]

A new storage type to use for results.

NotSet
result_serializer Union[ResultSerializer, Type[NotSet]]

A new serializer to use for results.

NotSet
result_storage_key Union[str, Type[NotSet]]

A new key for the persisted result to be stored at.

NotSet
timeout_seconds Union[int, float, None]

A new maximum time for the task to complete in seconds.

None
log_prints Union[bool, Type[NotSet]]

A new option for enabling or disabling redirection of print statements.

NotSet
refresh_cache Union[bool, Type[NotSet]]

A new option for enabling or disabling cache refresh.

NotSet
on_completion Optional[List[Callable[[Task, TaskRun, State], Union[Awaitable[None], None]]]]

A new list of callables to run when the task enters a completed state.

None
on_failure Optional[List[Callable[[Task, TaskRun, State], Union[Awaitable[None], None]]]]

A new list of callables to run when the task enters a failed state.

None
retry_condition_fn Optional[Callable[[Task, TaskRun, State], bool]]

An optional callable run when a task run returns a Failed state. Should return True if the task should continue to its retry policy, and False if the task should end as failed. Defaults to None, indicating the task should always continue to its retry policy.

None
viz_return_value Optional[Any]

An optional value to return when the task dependency tree is visualized.

None

Returns:

Type Description

A new Task instance.

Create a new task from an existing task and update the name

>>> @task(name="My task")
>>> def my_task():
>>>     return 1
>>>
>>> new_task = my_task.with_options(name="My new task")

Create a new task from an existing task and update the retry settings

>>> from random import randint
>>>
>>> @task(retries=1, retry_delay_seconds=5)
>>> def my_task():
>>>     x = randint(0, 5)
>>>     if x >= 3:  # Make a task that fails sometimes
>>>         raise ValueError("Retry me please!")
>>>     return x
>>>
>>> new_task = my_task.with_options(retries=5, retry_delay_seconds=2)

Use a task with updated options within a flow

>>> @task(name="My task")
>>> def my_task():
>>>     return 1
>>>
>>> @flow
>>> my_flow():
>>>     new_task = my_task.with_options(name="My new task")
>>>     new_task()
Source code in src/prefect/tasks.py
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
def with_options(
    self,
    *,
    name: Optional[str] = None,
    description: Optional[str] = None,
    tags: Optional[Iterable[str]] = None,
    cache_policy: Union[CachePolicy, Type[NotSet]] = NotSet,
    cache_key_fn: Optional[
        Callable[["TaskRunContext", Dict[str, Any]], Optional[str]]
    ] = None,
    task_run_name: Optional[Union[Callable[[], str], str]] = None,
    cache_expiration: Optional[datetime.timedelta] = None,
    retries: Union[int, Type[NotSet]] = NotSet,
    retry_delay_seconds: Union[
        float,
        int,
        List[float],
        Callable[[int], List[float]],
        Type[NotSet],
    ] = NotSet,
    retry_jitter_factor: Union[float, Type[NotSet]] = NotSet,
    persist_result: Union[bool, Type[NotSet]] = NotSet,
    result_storage: Union[ResultStorage, Type[NotSet]] = NotSet,
    result_serializer: Union[ResultSerializer, Type[NotSet]] = NotSet,
    result_storage_key: Union[str, Type[NotSet]] = NotSet,
    cache_result_in_memory: Optional[bool] = None,
    timeout_seconds: Union[int, float, None] = None,
    log_prints: Union[bool, Type[NotSet]] = NotSet,
    refresh_cache: Union[bool, Type[NotSet]] = NotSet,
    on_completion: Optional[
        List[Callable[["Task", TaskRun, State], Union[Awaitable[None], None]]]
    ] = None,
    on_failure: Optional[
        List[Callable[["Task", TaskRun, State], Union[Awaitable[None], None]]]
    ] = None,
    retry_condition_fn: Optional[Callable[["Task", TaskRun, State], bool]] = None,
    viz_return_value: Optional[Any] = None,
):
    """
    Create a new task from the current object, updating provided options.

    Args:
        name: A new name for the task.
        description: A new description for the task.
        tags: A new set of tags for the task. If given, existing tags are ignored,
            not merged.
        cache_key_fn: A new cache key function for the task.
        cache_expiration: A new cache expiration time for the task.
        task_run_name: An optional name to distinguish runs of this task; this name can be provided
            as a string template with the task's keyword arguments as variables,
            or a function that returns a string.
        retries: A new number of times to retry on task run failure.
        retry_delay_seconds: Optionally configures how long to wait before retrying
            the task after failure. This is only applicable if `retries` is nonzero.
            This setting can either be a number of seconds, a list of retry delays,
            or a callable that, given the total number of retries, generates a list
            of retry delays. If a number of seconds, that delay will be applied to
            all retries. If a list, each retry will wait for the corresponding delay
            before retrying. When passing a callable or a list, the number of
            configured retry delays cannot exceed 50.
        retry_jitter_factor: An optional factor that defines the factor to which a
            retry can be jittered in order to avoid a "thundering herd".
        persist_result: A new option for enabling or disabling result persistence.
        result_storage: A new storage type to use for results.
        result_serializer: A new serializer to use for results.
        result_storage_key: A new key for the persisted result to be stored at.
        timeout_seconds: A new maximum time for the task to complete in seconds.
        log_prints: A new option for enabling or disabling redirection of `print` statements.
        refresh_cache: A new option for enabling or disabling cache refresh.
        on_completion: A new list of callables to run when the task enters a completed state.
        on_failure: A new list of callables to run when the task enters a failed state.
        retry_condition_fn: An optional callable run when a task run returns a Failed state.
            Should return `True` if the task should continue to its retry policy, and `False`
            if the task should end as failed. Defaults to `None`, indicating the task should
            always continue to its retry policy.
        viz_return_value: An optional value to return when the task dependency tree is visualized.

    Returns:
        A new `Task` instance.

    Examples:

        Create a new task from an existing task and update the name

        >>> @task(name="My task")
        >>> def my_task():
        >>>     return 1
        >>>
        >>> new_task = my_task.with_options(name="My new task")

        Create a new task from an existing task and update the retry settings

        >>> from random import randint
        >>>
        >>> @task(retries=1, retry_delay_seconds=5)
        >>> def my_task():
        >>>     x = randint(0, 5)
        >>>     if x >= 3:  # Make a task that fails sometimes
        >>>         raise ValueError("Retry me please!")
        >>>     return x
        >>>
        >>> new_task = my_task.with_options(retries=5, retry_delay_seconds=2)

        Use a task with updated options within a flow

        >>> @task(name="My task")
        >>> def my_task():
        >>>     return 1
        >>>
        >>> @flow
        >>> my_flow():
        >>>     new_task = my_task.with_options(name="My new task")
        >>>     new_task()
    """
    return Task(
        fn=self.fn,
        name=name or self.name,
        description=description or self.description,
        tags=tags or copy(self.tags),
        cache_policy=cache_policy
        if cache_policy is not NotSet
        else self.cache_policy,
        cache_key_fn=cache_key_fn or self.cache_key_fn,
        cache_expiration=cache_expiration or self.cache_expiration,
        task_run_name=task_run_name,
        retries=retries if retries is not NotSet else self.retries,
        retry_delay_seconds=(
            retry_delay_seconds
            if retry_delay_seconds is not NotSet
            else self.retry_delay_seconds
        ),
        retry_jitter_factor=(
            retry_jitter_factor
            if retry_jitter_factor is not NotSet
            else self.retry_jitter_factor
        ),
        persist_result=(
            persist_result if persist_result is not NotSet else self.persist_result
        ),
        result_storage=(
            result_storage if result_storage is not NotSet else self.result_storage
        ),
        result_storage_key=(
            result_storage_key
            if result_storage_key is not NotSet
            else self.result_storage_key
        ),
        result_serializer=(
            result_serializer
            if result_serializer is not NotSet
            else self.result_serializer
        ),
        cache_result_in_memory=(
            cache_result_in_memory
            if cache_result_in_memory is not None
            else self.cache_result_in_memory
        ),
        timeout_seconds=(
            timeout_seconds if timeout_seconds is not None else self.timeout_seconds
        ),
        log_prints=(log_prints if log_prints is not NotSet else self.log_prints),
        refresh_cache=(
            refresh_cache if refresh_cache is not NotSet else self.refresh_cache
        ),
        on_completion=on_completion or self.on_completion_hooks,
        on_failure=on_failure or self.on_failure_hooks,
        retry_condition_fn=retry_condition_fn or self.retry_condition_fn,
        viz_return_value=viz_return_value or self.viz_return_value,
    )

Transaction

Bases: ContextModel

A base model for transaction state.

Source code in src/prefect/transactions.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
class Transaction(ContextModel):
    """
    A base model for transaction state.
    """

    store: Optional[RecordStore] = None
    key: Optional[str] = None
    children: List["Transaction"] = Field(default_factory=list)
    commit_mode: Optional[CommitMode] = None
    state: TransactionState = TransactionState.PENDING
    on_commit_hooks: List[Callable[["Transaction"], None]] = Field(default_factory=list)
    on_rollback_hooks: List[Callable[["Transaction"], None]] = Field(
        default_factory=list
    )
    overwrite: bool = False
    logger: Union[logging.Logger, logging.LoggerAdapter, None] = None
    _staged_value: Any = None
    __var__: ContextVar = ContextVar("transaction")

    def is_committed(self) -> bool:
        return self.state == TransactionState.COMMITTED

    def is_rolled_back(self) -> bool:
        return self.state == TransactionState.ROLLED_BACK

    def is_staged(self) -> bool:
        return self.state == TransactionState.STAGED

    def is_pending(self) -> bool:
        return self.state == TransactionState.PENDING

    def is_active(self) -> bool:
        return self.state == TransactionState.ACTIVE

    def __enter__(self):
        if self._token is not None:
            raise RuntimeError(
                "Context already entered. Context enter calls cannot be nested."
            )
        # set default commit behavior
        if self.commit_mode is None:
            parent = get_transaction()

            # either inherit from parent or set a default of eager
            if parent:
                self.commit_mode = parent.commit_mode
            else:
                self.commit_mode = CommitMode.LAZY

        # this needs to go before begin, which could set the state to committed
        self.state = TransactionState.ACTIVE
        self.begin()
        self._token = self.__var__.set(self)
        return self

    def __exit__(self, *exc_info):
        exc_type, exc_val, _ = exc_info
        if not self._token:
            raise RuntimeError(
                "Asymmetric use of context. Context exit called without an enter."
            )
        if exc_type:
            self.rollback()
            self.reset()
            raise exc_val

        if self.commit_mode == CommitMode.EAGER:
            self.commit()

        # if parent, let them take responsibility
        if self.get_parent():
            self.reset()
            return

        if self.commit_mode == CommitMode.OFF:
            # if no one took responsibility to commit, rolling back
            # note that rollback returns if already committed
            self.rollback()
        elif self.commit_mode == CommitMode.LAZY:
            # no one left to take responsibility for committing
            self.commit()

        self.reset()

    def begin(self):
        # currently we only support READ_COMMITTED isolation
        # i.e., no locking behavior
        if (
            not self.overwrite
            and self.store
            and self.key
            and self.store.exists(key=self.key)
        ):
            self.state = TransactionState.COMMITTED

    def read(self) -> BaseResult:
        if self.store and self.key:
            return self.store.read(key=self.key)
        else:
            return {}  # TODO: Determine what this should be

    def reset(self) -> None:
        parent = self.get_parent()

        if parent:
            # parent takes responsibility
            parent.add_child(self)

        if self._token:
            self.__var__.reset(self._token)
            self._token = None

        # do this below reset so that get_transaction() returns the relevant txn
        if parent and self.state == TransactionState.ROLLED_BACK:
            parent.rollback()

    def add_child(self, transaction: "Transaction") -> None:
        self.children.append(transaction)

    def get_parent(self) -> Optional["Transaction"]:
        prev_var = getattr(self._token, "old_value")
        if prev_var != Token.MISSING:
            parent = prev_var
        else:
            parent = None
        return parent

    def commit(self) -> bool:
        if self.state in [TransactionState.ROLLED_BACK, TransactionState.COMMITTED]:
            return False

        try:
            hook_name = None

            for child in self.children:
                child.commit()

            for hook in self.on_commit_hooks:
                hook_name = _get_hook_name(hook)
                hook(self)

            if self.store and self.key:
                self.store.write(key=self.key, value=self._staged_value)
            self.state = TransactionState.COMMITTED
            return True
        except Exception:
            if self.logger:
                if hook_name:
                    msg = (
                        f"An error was encountered while running commit hook {hook_name!r}",
                    )
                else:
                    msg = (
                        f"An error was encountered while committing transaction {self.key!r}",
                    )
                self.logger.exception(
                    msg,
                    exc_info=True,
                )
            self.rollback()
            return False

    def stage(
        self,
        value: BaseResult,
        on_rollback_hooks: Optional[List] = None,
        on_commit_hooks: Optional[List] = None,
    ) -> None:
        """
        Stage a value to be committed later.
        """
        on_commit_hooks = on_commit_hooks or []
        on_rollback_hooks = on_rollback_hooks or []

        if self.state != TransactionState.COMMITTED:
            self._staged_value = value
            self.on_rollback_hooks += on_rollback_hooks
            self.on_commit_hooks += on_commit_hooks
            self.state = TransactionState.STAGED

    def rollback(self) -> bool:
        if self.state in [TransactionState.ROLLED_BACK, TransactionState.COMMITTED]:
            return False

        try:
            for hook in reversed(self.on_rollback_hooks):
                hook_name = _get_hook_name(hook)
                hook(self)

            self.state = TransactionState.ROLLED_BACK

            for child in reversed(self.children):
                child.rollback()

            return True
        except Exception:
            if self.logger:
                self.logger.exception(
                    f"An error was encountered while running rollback hook {hook_name!r}",
                    exc_info=True,
                )
            return False

    @classmethod
    def get_active(cls: Type[Self]) -> Optional[Self]:
        return cls.__var__.get(None)

stage(value, on_rollback_hooks=None, on_commit_hooks=None)

Stage a value to be committed later.

Source code in src/prefect/transactions.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def stage(
    self,
    value: BaseResult,
    on_rollback_hooks: Optional[List] = None,
    on_commit_hooks: Optional[List] = None,
) -> None:
    """
    Stage a value to be committed later.
    """
    on_commit_hooks = on_commit_hooks or []
    on_rollback_hooks = on_rollback_hooks or []

    if self.state != TransactionState.COMMITTED:
        self._staged_value = value
        self.on_rollback_hooks += on_rollback_hooks
        self.on_commit_hooks += on_commit_hooks
        self.state = TransactionState.STAGED

allow_failure

Bases: BaseAnnotation[T]

Wrapper for states or futures.

Indicates that the upstream run for this input can be failed.

Generally, Prefect will not allow a downstream run to start if any of its inputs are failed. This annotation allows you to opt into receiving a failed input downstream.

If the input is from a failed run, the attached exception will be passed to your function.

Source code in src/prefect/utilities/annotations.py
46
47
48
49
50
51
52
53
54
55
56
57
58
class allow_failure(BaseAnnotation[T]):
    """
    Wrapper for states or futures.

    Indicates that the upstream run for this input can be failed.

    Generally, Prefect will not allow a downstream run to start if any of its inputs
    are failed. This annotation allows you to opt into receiving a failed input
    downstream.

    If the input is from a failed run, the attached exception will be passed to your
    function.
    """

unmapped

Bases: BaseAnnotation[T]

Wrapper for iterables.

Indicates that this input should be sent as-is to all runs created during a mapping operation instead of being split.

Source code in src/prefect/utilities/annotations.py
33
34
35
36
37
38
39
40
41
42
43
class unmapped(BaseAnnotation[T]):
    """
    Wrapper for iterables.

    Indicates that this input should be sent as-is to all runs created during a mapping
    operation instead of being split.
    """

    def __getitem__(self, _) -> T:
        # Internally, this acts as an infinite array where all items are the same value
        return self.unwrap()

deploy(*deployments, work_pool_name=None, image=None, build=True, push=True, print_next_steps_message=True, ignore_warnings=False) async

Deploy the provided list of deployments to dynamic infrastructure via a work pool.

By default, calling this function will build a Docker image for the deployments, push it to a registry, and create each deployment via the Prefect API that will run the corresponding flow on the given schedule.

If you want to use an existing image, you can pass build=False to skip building and pushing an image.

Parameters:

Name Type Description Default
*deployments RunnerDeployment

A list of deployments to deploy.

()
work_pool_name Optional[str]

The name of the work pool to use for these deployments. Defaults to the value of PREFECT_DEFAULT_WORK_POOL_NAME.

None
image Optional[Union[str, DockerImage]]

The name of the Docker image to build, including the registry and repository. Pass a DockerImage instance to customize the Dockerfile used and build arguments.

None
build bool

Whether or not to build a new image for the flow. If False, the provided image will be used as-is and pulled at runtime.

True
push bool

Whether or not to skip pushing the built image to a registry.

True
print_next_steps_message bool

Whether or not to print a message with next steps after deploying the deployments.

True

Returns:

Type Description
List[UUID]

A list of deployment IDs for the created/updated deployments.

Examples:

Deploy a group of flows to a work pool:

from prefect import deploy, flow

@flow(log_prints=True)
def local_flow():
    print("I'm a locally defined flow!")

if __name__ == "__main__":
    deploy(
        local_flow.to_deployment(name="example-deploy-local-flow"),
        flow.from_source(
            source="https://github.com/org/repo.git",
            entrypoint="flows.py:my_flow",
        ).to_deployment(
            name="example-deploy-remote-flow",
        ),
        work_pool_name="my-work-pool",
        image="my-registry/my-image:dev",
    )
Source code in src/prefect/deployments/runner.py
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
@sync_compatible
async def deploy(
    *deployments: RunnerDeployment,
    work_pool_name: Optional[str] = None,
    image: Optional[Union[str, DockerImage]] = None,
    build: bool = True,
    push: bool = True,
    print_next_steps_message: bool = True,
    ignore_warnings: bool = False,
) -> List[UUID]:
    """
    Deploy the provided list of deployments to dynamic infrastructure via a
    work pool.

    By default, calling this function will build a Docker image for the deployments, push it to a
    registry, and create each deployment via the Prefect API that will run the corresponding
    flow on the given schedule.

    If you want to use an existing image, you can pass `build=False` to skip building and pushing
    an image.

    Args:
        *deployments: A list of deployments to deploy.
        work_pool_name: The name of the work pool to use for these deployments. Defaults to
            the value of `PREFECT_DEFAULT_WORK_POOL_NAME`.
        image: The name of the Docker image to build, including the registry and
            repository. Pass a DockerImage instance to customize the Dockerfile used
            and build arguments.
        build: Whether or not to build a new image for the flow. If False, the provided
            image will be used as-is and pulled at runtime.
        push: Whether or not to skip pushing the built image to a registry.
        print_next_steps_message: Whether or not to print a message with next steps
            after deploying the deployments.

    Returns:
        A list of deployment IDs for the created/updated deployments.

    Examples:
        Deploy a group of flows to a work pool:

        ```python
        from prefect import deploy, flow

        @flow(log_prints=True)
        def local_flow():
            print("I'm a locally defined flow!")

        if __name__ == "__main__":
            deploy(
                local_flow.to_deployment(name="example-deploy-local-flow"),
                flow.from_source(
                    source="https://github.com/org/repo.git",
                    entrypoint="flows.py:my_flow",
                ).to_deployment(
                    name="example-deploy-remote-flow",
                ),
                work_pool_name="my-work-pool",
                image="my-registry/my-image:dev",
            )
        ```
    """
    work_pool_name = work_pool_name or PREFECT_DEFAULT_WORK_POOL_NAME.value()

    if not image and not all(
        d.storage or d.entrypoint_type == EntrypointType.MODULE_PATH
        for d in deployments
    ):
        raise ValueError(
            "Either an image or remote storage location must be provided when deploying"
            " a deployment."
        )

    if not work_pool_name:
        raise ValueError(
            "A work pool name must be provided when deploying a deployment. Either"
            " provide a work pool name when calling `deploy` or set"
            " `PREFECT_DEFAULT_WORK_POOL_NAME` in your profile."
        )

    if image and isinstance(image, str):
        image_name, image_tag = parse_image_tag(image)
        image = DockerImage(name=image_name, tag=image_tag)

    try:
        async with get_client() as client:
            work_pool = await client.read_work_pool(work_pool_name)
    except ObjectNotFound as exc:
        raise ValueError(
            f"Could not find work pool {work_pool_name!r}. Please create it before"
            " deploying this flow."
        ) from exc

    is_docker_based_work_pool = get_from_dict(
        work_pool.base_job_template, "variables.properties.image", False
    )
    is_block_based_work_pool = get_from_dict(
        work_pool.base_job_template, "variables.properties.block", False
    )
    # carve out an exception for block based work pools that only have a block in their base job template
    console = Console()
    if not is_docker_based_work_pool and not is_block_based_work_pool:
        if image:
            raise ValueError(
                f"Work pool {work_pool_name!r} does not support custom Docker images."
                " Please use a work pool with an `image` variable in its base job template"
                " or specify a remote storage location for the flow with `.from_source`."
                " If you are attempting to deploy a flow to a local process work pool,"
                " consider using `flow.serve` instead. See the documentation for more"
                " information: https://docs.prefect.io/latest/concepts/flows/#serving-a-flow"
            )
        elif work_pool.type == "process" and not ignore_warnings:
            console.print(
                "Looks like you're deploying to a process work pool. If you're creating a"
                " deployment for local development, calling `.serve` on your flow is a great"
                " way to get started. See the documentation for more information:"
                " https://docs.prefect.io/latest/concepts/flows/#serving-a-flow. "
                " Set `ignore_warnings=True` to suppress this message.",
                style="yellow",
            )

    is_managed_pool = work_pool.is_managed_pool
    if is_managed_pool:
        build = False
        push = False

    if image and build:
        with Progress(
            SpinnerColumn(),
            TextColumn(f"Building image {image.reference}..."),
            transient=True,
            console=console,
        ) as progress:
            docker_build_task = progress.add_task("docker_build", total=1)
            image.build()

            progress.update(docker_build_task, completed=1)
            console.print(
                f"Successfully built image {image.reference!r}", style="green"
            )

    if image and build and push:
        with Progress(
            SpinnerColumn(),
            TextColumn("Pushing image..."),
            transient=True,
            console=console,
        ) as progress:
            docker_push_task = progress.add_task("docker_push", total=1)

            image.push()

            progress.update(docker_push_task, completed=1)

        console.print(f"Successfully pushed image {image.reference!r}", style="green")

    deployment_exceptions = []
    deployment_ids = []
    image_ref = image.reference if image else None
    for deployment in track(
        deployments,
        description="Creating/updating deployments...",
        console=console,
        transient=True,
    ):
        try:
            deployment_ids.append(
                await deployment.apply(image=image_ref, work_pool_name=work_pool_name)
            )
        except Exception as exc:
            if len(deployments) == 1:
                raise
            deployment_exceptions.append({"deployment": deployment, "exc": exc})

    if deployment_exceptions:
        console.print(
            "Encountered errors while creating/updating deployments:\n",
            style="orange_red1",
        )
    else:
        console.print("Successfully created/updated all deployments!\n", style="green")

    complete_failure = len(deployment_exceptions) == len(deployments)

    table = Table(
        title="Deployments",
        show_lines=True,
    )

    table.add_column(header="Name", style="blue", no_wrap=True)
    table.add_column(header="Status", style="blue", no_wrap=True)
    table.add_column(header="Details", style="blue")

    for deployment in deployments:
        errored_deployment = next(
            (d for d in deployment_exceptions if d["deployment"] == deployment),
            None,
        )
        if errored_deployment:
            table.add_row(
                f"{deployment.flow_name}/{deployment.name}",
                "failed",
                str(errored_deployment["exc"]),
                style="red",
            )
        else:
            table.add_row(f"{deployment.flow_name}/{deployment.name}", "applied")
    console.print(table)

    if print_next_steps_message and not complete_failure:
        if not work_pool.is_push_pool and not work_pool.is_managed_pool:
            console.print(
                "\nTo execute flow runs from these deployments, start a worker in a"
                " separate terminal that pulls work from the"
                f" {work_pool_name!r} work pool:"
            )
            console.print(
                f"\n\t$ prefect worker start --pool {work_pool_name!r}",
                style="blue",
            )
        console.print(
            "\nTo trigger any of these deployments, use the"
            " following command:\n[blue]\n\t$ prefect deployment run"
            " [DEPLOYMENT_NAME]\n[/]"
        )

        if PREFECT_UI_URL:
            console.print(
                "\nYou can also trigger your deployments via the Prefect UI:"
                f" [blue]{PREFECT_UI_URL.value()}/deployments[/]\n"
            )

    return deployment_ids

flow(__fn=None, *, name=None, version=None, flow_run_name=None, retries=None, retry_delay_seconds=None, task_runner=None, description=None, timeout_seconds=None, validate_parameters=True, persist_result=None, result_storage=None, result_serializer=None, cache_result_in_memory=True, log_prints=None, on_completion=None, on_failure=None, on_cancellation=None, on_crashed=None, on_running=None)

Decorator to designate a function as a Prefect workflow.

This decorator may be used for asynchronous or synchronous functions.

Flow parameters must be serializable by Pydantic.

Parameters:

Name Type Description Default
name Optional[str]

An optional name for the flow; if not provided, the name will be inferred from the given function.

None
version Optional[str]

An optional version string for the flow; if not provided, we will attempt to create a version string as a hash of the file containing the wrapped function; if the file cannot be located, the version will be null.

None
flow_run_name Optional[Union[Callable[[], str], str]]

An optional name to distinguish runs of this flow; this name can be provided as a string template with the flow's parameters as variables, or a function that returns a string.

None
retries Optional[int]

An optional number of times to retry on flow run failure.

None
retry_delay_seconds Union[int, float, None]

An optional number of seconds to wait before retrying the flow after failure. This is only applicable if retries is nonzero.

None
task_runner Optional[TaskRunner]

An optional task runner to use for task execution within the flow; if not provided, a ConcurrentTaskRunner will be instantiated.

None
description Optional[str]

An optional string description for the flow; if not provided, the description will be pulled from the docstring for the decorated function.

None
timeout_seconds Union[int, float, None]

An optional number of seconds indicating a maximum runtime for the flow. If the flow exceeds this runtime, it will be marked as failed. Flow execution may continue until the next task is called.

None
validate_parameters bool

By default, parameters passed to flows are validated by Pydantic. This will check that input values conform to the annotated types on the function. Where possible, values will be coerced into the correct type; for example, if a parameter is defined as x: int and "5" is passed, it will be resolved to 5. If set to False, no validation will be performed on flow parameters.

True
persist_result Optional[bool]

An optional toggle indicating whether the result of this flow should be persisted to result storage. Defaults to None, which indicates that Prefect should choose whether the result should be persisted depending on the features being used.

None
result_storage Optional[ResultStorage]

An optional block to use to persist the result of this flow. This value will be used as the default for any tasks in this flow. If not provided, the local file system will be used unless called as a subflow, at which point the default will be loaded from the parent flow.

None
result_serializer Optional[ResultSerializer]

An optional serializer to use to serialize the result of this flow for persistence. This value will be used as the default for any tasks in this flow. If not provided, the value of PREFECT_RESULTS_DEFAULT_SERIALIZER will be used unless called as a subflow, at which point the default will be loaded from the parent flow.

None
cache_result_in_memory bool

An optional toggle indicating whether the cached result of a running the flow should be stored in memory. Defaults to True.

True
log_prints Optional[bool]

If set, print statements in the flow will be redirected to the Prefect logger for the flow run. Defaults to None, which indicates that the value from the parent flow should be used. If this is a parent flow, the default is pulled from the PREFECT_LOGGING_LOG_PRINTS setting.

None
on_completion Optional[List[Callable[[Flow, FlowRun, State], Union[Awaitable[None], None]]]]

An optional list of functions to call when the flow run is completed. Each function should accept three arguments: the flow, the flow run, and the final state of the flow run.

None
on_failure Optional[List[Callable[[Flow, FlowRun, State], Union[Awaitable[None], None]]]]

An optional list of functions to call when the flow run fails. Each function should accept three arguments: the flow, the flow run, and the final state of the flow run.

None
on_cancellation Optional[List[Callable[[Flow, FlowRun, State], None]]]

An optional list of functions to call when the flow run is cancelled. These functions will be passed the flow, flow run, and final state.

None
on_crashed Optional[List[Callable[[Flow, FlowRun, State], None]]]

An optional list of functions to call when the flow run crashes. Each function should accept three arguments: the flow, the flow run, and the final state of the flow run.

None
on_running Optional[List[Callable[[Flow, FlowRun, State], None]]]

An optional list of functions to call when the flow run is started. Each function should accept three arguments: the flow, the flow run, and the current state

None

Returns:

Type Description

A callable Flow object which, when called, will run the flow and return its

final state.

Examples:

Define a simple flow

>>> from prefect import flow
>>> @flow
>>> def add(x, y):
>>>     return x + y

Define an async flow

>>> @flow
>>> async def add(x, y):
>>>     return x + y

Define a flow with a version and description

>>> @flow(version="first-flow", description="This flow is empty!")
>>> def my_flow():
>>>     pass

Define a flow with a custom name

>>> @flow(name="The Ultimate Flow")
>>> def my_flow():
>>>     pass

Define a flow that submits its tasks to dask

>>> from prefect_dask.task_runners import DaskTaskRunner
>>>
>>> @flow(task_runner=DaskTaskRunner)
>>> def my_flow():
>>>     pass
Source code in src/prefect/flows.py
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
def flow(
    __fn=None,
    *,
    name: Optional[str] = None,
    version: Optional[str] = None,
    flow_run_name: Optional[Union[Callable[[], str], str]] = None,
    retries: Optional[int] = None,
    retry_delay_seconds: Union[int, float, None] = None,
    task_runner: Optional[TaskRunner] = None,
    description: Optional[str] = None,
    timeout_seconds: Union[int, float, None] = None,
    validate_parameters: bool = True,
    persist_result: Optional[bool] = None,
    result_storage: Optional[ResultStorage] = None,
    result_serializer: Optional[ResultSerializer] = None,
    cache_result_in_memory: bool = True,
    log_prints: Optional[bool] = None,
    on_completion: Optional[
        List[Callable[[FlowSchema, FlowRun, State], Union[Awaitable[None], None]]]
    ] = None,
    on_failure: Optional[
        List[Callable[[FlowSchema, FlowRun, State], Union[Awaitable[None], None]]]
    ] = None,
    on_cancellation: Optional[
        List[Callable[[FlowSchema, FlowRun, State], None]]
    ] = None,
    on_crashed: Optional[List[Callable[[FlowSchema, FlowRun, State], None]]] = None,
    on_running: Optional[List[Callable[[FlowSchema, FlowRun, State], None]]] = None,
):
    """
    Decorator to designate a function as a Prefect workflow.

    This decorator may be used for asynchronous or synchronous functions.

    Flow parameters must be serializable by Pydantic.

    Args:
        name: An optional name for the flow; if not provided, the name will be inferred
            from the given function.
        version: An optional version string for the flow; if not provided, we will
            attempt to create a version string as a hash of the file containing the
            wrapped function; if the file cannot be located, the version will be null.
        flow_run_name: An optional name to distinguish runs of this flow; this name can
            be provided as a string template with the flow's parameters as variables,
            or a function that returns a string.
        retries: An optional number of times to retry on flow run failure.
        retry_delay_seconds: An optional number of seconds to wait before retrying the
            flow after failure. This is only applicable if `retries` is nonzero.
        task_runner: An optional task runner to use for task execution within the flow; if
            not provided, a `ConcurrentTaskRunner` will be instantiated.
        description: An optional string description for the flow; if not provided, the
            description will be pulled from the docstring for the decorated function.
        timeout_seconds: An optional number of seconds indicating a maximum runtime for
            the flow. If the flow exceeds this runtime, it will be marked as failed.
            Flow execution may continue until the next task is called.
        validate_parameters: By default, parameters passed to flows are validated by
            Pydantic. This will check that input values conform to the annotated types
            on the function. Where possible, values will be coerced into the correct
            type; for example, if a parameter is defined as `x: int` and "5" is passed,
            it will be resolved to `5`. If set to `False`, no validation will be
            performed on flow parameters.
        persist_result: An optional toggle indicating whether the result of this flow
            should be persisted to result storage. Defaults to `None`, which indicates
            that Prefect should choose whether the result should be persisted depending on
            the features being used.
        result_storage: An optional block to use to persist the result of this flow.
            This value will be used as the default for any tasks in this flow.
            If not provided, the local file system will be used unless called as
            a subflow, at which point the default will be loaded from the parent flow.
        result_serializer: An optional serializer to use to serialize the result of this
            flow for persistence. This value will be used as the default for any tasks
            in this flow. If not provided, the value of `PREFECT_RESULTS_DEFAULT_SERIALIZER`
            will be used unless called as a subflow, at which point the default will be
            loaded from the parent flow.
        cache_result_in_memory: An optional toggle indicating whether the cached result of
            a running the flow should be stored in memory. Defaults to `True`.
        log_prints: If set, `print` statements in the flow will be redirected to the
            Prefect logger for the flow run. Defaults to `None`, which indicates that
            the value from the parent flow should be used. If this is a parent flow,
            the default is pulled from the `PREFECT_LOGGING_LOG_PRINTS` setting.
        on_completion: An optional list of functions to call when the flow run is
            completed. Each function should accept three arguments: the flow, the flow
            run, and the final state of the flow run.
        on_failure: An optional list of functions to call when the flow run fails. Each
            function should accept three arguments: the flow, the flow run, and the
            final state of the flow run.
        on_cancellation: An optional list of functions to call when the flow run is
            cancelled. These functions will be passed the flow, flow run, and final state.
        on_crashed: An optional list of functions to call when the flow run crashes. Each
            function should accept three arguments: the flow, the flow run, and the
            final state of the flow run.
        on_running: An optional list of functions to call when the flow run is started. Each
            function should accept three arguments: the flow, the flow run, and the current state

    Returns:
        A callable `Flow` object which, when called, will run the flow and return its
        final state.

    Examples:
        Define a simple flow

        >>> from prefect import flow
        >>> @flow
        >>> def add(x, y):
        >>>     return x + y

        Define an async flow

        >>> @flow
        >>> async def add(x, y):
        >>>     return x + y

        Define a flow with a version and description

        >>> @flow(version="first-flow", description="This flow is empty!")
        >>> def my_flow():
        >>>     pass

        Define a flow with a custom name

        >>> @flow(name="The Ultimate Flow")
        >>> def my_flow():
        >>>     pass

        Define a flow that submits its tasks to dask

        >>> from prefect_dask.task_runners import DaskTaskRunner
        >>>
        >>> @flow(task_runner=DaskTaskRunner)
        >>> def my_flow():
        >>>     pass
    """
    if __fn:
        if isinstance(__fn, (classmethod, staticmethod)):
            method_decorator = type(__fn).__name__
            raise TypeError(f"@{method_decorator} should be applied on top of @flow")
        return cast(
            Flow[P, R],
            Flow(
                fn=__fn,
                name=name,
                version=version,
                flow_run_name=flow_run_name,
                task_runner=task_runner,
                description=description,
                timeout_seconds=timeout_seconds,
                validate_parameters=validate_parameters,
                retries=retries,
                retry_delay_seconds=retry_delay_seconds,
                persist_result=persist_result,
                result_storage=result_storage,
                result_serializer=result_serializer,
                cache_result_in_memory=cache_result_in_memory,
                log_prints=log_prints,
                on_completion=on_completion,
                on_failure=on_failure,
                on_cancellation=on_cancellation,
                on_crashed=on_crashed,
                on_running=on_running,
            ),
        )
    else:
        return cast(
            Callable[[Callable[P, R]], Flow[P, R]],
            partial(
                flow,
                name=name,
                version=version,
                flow_run_name=flow_run_name,
                task_runner=task_runner,
                description=description,
                timeout_seconds=timeout_seconds,
                validate_parameters=validate_parameters,
                retries=retries,
                retry_delay_seconds=retry_delay_seconds,
                persist_result=persist_result,
                result_storage=result_storage,
                result_serializer=result_serializer,
                cache_result_in_memory=cache_result_in_memory,
                log_prints=log_prints,
                on_completion=on_completion,
                on_failure=on_failure,
                on_cancellation=on_cancellation,
                on_crashed=on_crashed,
                on_running=on_running,
            ),
        )

get_client(httpx_settings=None, sync_client=False)

Retrieve a HTTP client for communicating with the Prefect REST API.

The client must be context managed; for example:

async with get_client() as client:
    await client.hello()

To return a synchronous client, pass sync_client=True:

with get_client(sync_client=True) as client:
    client.hello()
Source code in src/prefect/client/orchestration.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
def get_client(
    httpx_settings: Optional[Dict[str, Any]] = None, sync_client: bool = False
):
    """
    Retrieve a HTTP client for communicating with the Prefect REST API.

    The client must be context managed; for example:

    ```python
    async with get_client() as client:
        await client.hello()
    ```

    To return a synchronous client, pass sync_client=True:

    ```python
    with get_client(sync_client=True) as client:
        client.hello()
    ```
    """
    import prefect.context

    settings_ctx = prefect.context.get_settings_context()

    # try to load clients from a client context, if possible
    # only load clients that match the provided config / loop
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = None

    if client_ctx := prefect.context.ClientContext.get():
        if (
            sync_client
            and client_ctx.sync_client
            and client_ctx._httpx_settings == httpx_settings
        ):
            return client_ctx.sync_client
        elif (
            not sync_client
            and client_ctx.async_client
            and client_ctx._httpx_settings == httpx_settings
            and loop in (client_ctx.async_client._loop, None)
        ):
            return client_ctx.async_client

    api = PREFECT_API_URL.value()

    if not api:
        # create an ephemeral API if none was provided
        from prefect.server.api.server import create_app

        api = create_app(settings_ctx.settings, ephemeral=True)

    if sync_client:
        return SyncPrefectClient(
            api,
            api_key=PREFECT_API_KEY.value(),
            httpx_settings=httpx_settings,
        )
    else:
        return PrefectClient(
            api,
            api_key=PREFECT_API_KEY.value(),
            httpx_settings=httpx_settings,
        )

get_run_logger(context=None, **kwargs)

Get a Prefect logger for the current task run or flow run.

The logger will be named either prefect.task_runs or prefect.flow_runs. Contextual data about the run will be attached to the log records.

These loggers are connected to the APILogHandler by default to send log records to the API.

Parameters:

Name Type Description Default
context RunContext

A specific context may be provided as an override. By default, the context is inferred from global state and this should not be needed.

None
**kwargs str

Additional keyword arguments will be attached to the log records in addition to the run metadata

{}

Raises:

Type Description
MissingContextError

If no context can be found

Source code in src/prefect/logging/loggers.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def get_run_logger(
    context: "RunContext" = None, **kwargs: str
) -> Union[logging.Logger, logging.LoggerAdapter]:
    """
    Get a Prefect logger for the current task run or flow run.

    The logger will be named either `prefect.task_runs` or `prefect.flow_runs`.
    Contextual data about the run will be attached to the log records.

    These loggers are connected to the `APILogHandler` by default to send log records to
    the API.

    Arguments:
        context: A specific context may be provided as an override. By default, the
            context is inferred from global state and this should not be needed.
        **kwargs: Additional keyword arguments will be attached to the log records in
            addition to the run metadata

    Raises:
        MissingContextError: If no context can be found
    """
    # Check for existing contexts
    task_run_context = prefect.context.TaskRunContext.get()
    flow_run_context = prefect.context.FlowRunContext.get()

    # Apply the context override
    if context:
        if isinstance(context, prefect.context.FlowRunContext):
            flow_run_context = context
        elif isinstance(context, prefect.context.TaskRunContext):
            task_run_context = context
        else:
            raise TypeError(
                f"Received unexpected type {type(context).__name__!r} for context. "
                "Expected one of 'None', 'FlowRunContext', or 'TaskRunContext'."
            )

    # Determine if this is a task or flow run logger
    if task_run_context:
        logger = task_run_logger(
            task_run=task_run_context.task_run,
            task=task_run_context.task,
            flow_run=flow_run_context.flow_run if flow_run_context else None,
            flow=flow_run_context.flow if flow_run_context else None,
            **kwargs,
        )
    elif flow_run_context:
        logger = flow_run_logger(
            flow_run=flow_run_context.flow_run, flow=flow_run_context.flow, **kwargs
        )
    elif (
        get_logger("prefect.flow_run").disabled
        and get_logger("prefect.task_run").disabled
    ):
        logger = logging.getLogger("null")
    else:
        raise MissingContextError("There is no active flow or task run context.")

    return logger

pause_flow_run(wait_for_input=None, timeout=3600, poll_interval=10, key=None) async

Pauses the current flow run by blocking execution until resumed.

When called within a flow run, execution will block and no downstream tasks will run until the flow is resumed. Task runs that have already started will continue running. A timeout parameter can be passed that will fail the flow run if it has not been resumed within the specified time.

Parameters:

Name Type Description Default
timeout int

the number of seconds to wait for the flow to be resumed before failing. Defaults to 1 hour (3600 seconds). If the pause timeout exceeds any configured flow-level timeout, the flow might fail even after resuming.

3600
poll_interval int

The number of seconds between checking whether the flow has been resumed. Defaults to 10 seconds.

10
key Optional[str]

An optional key to prevent calling pauses more than once. This defaults to the number of pauses observed by the flow so far, and prevents pauses that use the "reschedule" option from running the same pause twice. A custom key can be supplied for custom pausing behavior.

None
wait_for_input Optional[Type[T]]

a subclass of RunInput or any type supported by Pydantic. If provided when the flow pauses, the flow will wait for the input to be provided before resuming. If the flow is resumed without providing the input, the flow will fail. If the flow is resumed with the input, the flow will resume and the input will be loaded and returned from this function.

None
@task
def task_one():
    for i in range(3):
        sleep(1)

@flow
def my_flow():
    terminal_state = task_one.submit(return_state=True)
    if terminal_state.type == StateType.COMPLETED:
        print("Task one succeeded! Pausing flow run..")
        pause_flow_run(timeout=2)
    else:
        print("Task one failed. Skipping pause flow run..")
Source code in src/prefect/flow_runs.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
@sync_compatible
async def pause_flow_run(
    wait_for_input: Optional[Type[T]] = None,
    timeout: int = 3600,
    poll_interval: int = 10,
    key: Optional[str] = None,
) -> Optional[T]:
    """
    Pauses the current flow run by blocking execution until resumed.

    When called within a flow run, execution will block and no downstream tasks will
    run until the flow is resumed. Task runs that have already started will continue
    running. A timeout parameter can be passed that will fail the flow run if it has not
    been resumed within the specified time.

    Args:
        timeout: the number of seconds to wait for the flow to be resumed before
            failing. Defaults to 1 hour (3600 seconds). If the pause timeout exceeds
            any configured flow-level timeout, the flow might fail even after resuming.
        poll_interval: The number of seconds between checking whether the flow has been
            resumed. Defaults to 10 seconds.
        key: An optional key to prevent calling pauses more than once. This defaults to
            the number of pauses observed by the flow so far, and prevents pauses that
            use the "reschedule" option from running the same pause twice. A custom key
            can be supplied for custom pausing behavior.
        wait_for_input: a subclass of `RunInput` or any type supported by
            Pydantic. If provided when the flow pauses, the flow will wait for the
            input to be provided before resuming. If the flow is resumed without
            providing the input, the flow will fail. If the flow is resumed with the
            input, the flow will resume and the input will be loaded and returned
            from this function.

    Example:
    ```python
    @task
    def task_one():
        for i in range(3):
            sleep(1)

    @flow
    def my_flow():
        terminal_state = task_one.submit(return_state=True)
        if terminal_state.type == StateType.COMPLETED:
            print("Task one succeeded! Pausing flow run..")
            pause_flow_run(timeout=2)
        else:
            print("Task one failed. Skipping pause flow run..")
    ```

    """
    return await _in_process_pause(
        timeout=timeout,
        poll_interval=poll_interval,
        key=key,
        wait_for_input=wait_for_input,
    )

resume_flow_run(flow_run_id, run_input=None) async

Resumes a paused flow.

Parameters:

Name Type Description Default
flow_run_id

the flow_run_id to resume

required
run_input Optional[Dict]

a dictionary of inputs to provide to the flow run.

None
Source code in src/prefect/flow_runs.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
@sync_compatible
async def resume_flow_run(flow_run_id, run_input: Optional[Dict] = None):
    """
    Resumes a paused flow.

    Args:
        flow_run_id: the flow_run_id to resume
        run_input: a dictionary of inputs to provide to the flow run.
    """
    client = get_client()
    async with client:
        flow_run = await client.read_flow_run(flow_run_id)

        if not flow_run.state.is_paused():
            raise NotPausedError("Cannot resume a run that isn't paused!")

        response = await client.resume_flow_run(flow_run_id, run_input=run_input)

    if response.status == SetStateStatus.REJECT:
        if response.state.type == StateType.FAILED:
            raise FlowPauseTimeout("Flow run can no longer be resumed.")
        else:
            raise RuntimeError(f"Cannot resume this run: {response.details.reason}")

serve(*args, pause_on_shutdown=True, print_starting_message=True, limit=None, **kwargs) async

Serve the provided list of deployments.

Parameters:

Name Type Description Default
*args RunnerDeployment

A list of deployments to serve.

()
pause_on_shutdown bool

A boolean for whether or not to automatically pause deployment schedules on shutdown.

True
print_starting_message bool

Whether or not to print message to the console on startup.

True
limit Optional[int]

The maximum number of runs that can be executed concurrently.

None
**kwargs

Additional keyword arguments to pass to the runner.

{}

Examples:

Prepare two deployments and serve them:

import datetime

from prefect import flow, serve

@flow
def my_flow(name):
    print(f"hello {name}")

@flow
def my_other_flow(name):
    print(f"goodbye {name}")

if __name__ == "__main__":
    # Run once a day
    hello_deploy = my_flow.to_deployment(
        "hello", tags=["dev"], interval=datetime.timedelta(days=1)
    )

    # Run every Sunday at 4:00 AM
    bye_deploy = my_other_flow.to_deployment(
        "goodbye", tags=["dev"], cron="0 4 * * sun"
    )

    serve(hello_deploy, bye_deploy)
Source code in src/prefect/flows.py
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
@sync_compatible
async def serve(
    *args: "RunnerDeployment",
    pause_on_shutdown: bool = True,
    print_starting_message: bool = True,
    limit: Optional[int] = None,
    **kwargs,
) -> NoReturn:
    """
    Serve the provided list of deployments.

    Args:
        *args: A list of deployments to serve.
        pause_on_shutdown: A boolean for whether or not to automatically pause
            deployment schedules on shutdown.
        print_starting_message: Whether or not to print message to the console
            on startup.
        limit: The maximum number of runs that can be executed concurrently.
        **kwargs: Additional keyword arguments to pass to the runner.

    Examples:
        Prepare two deployments and serve them:

        ```python
        import datetime

        from prefect import flow, serve

        @flow
        def my_flow(name):
            print(f"hello {name}")

        @flow
        def my_other_flow(name):
            print(f"goodbye {name}")

        if __name__ == "__main__":
            # Run once a day
            hello_deploy = my_flow.to_deployment(
                "hello", tags=["dev"], interval=datetime.timedelta(days=1)
            )

            # Run every Sunday at 4:00 AM
            bye_deploy = my_other_flow.to_deployment(
                "goodbye", tags=["dev"], cron="0 4 * * sun"
            )

            serve(hello_deploy, bye_deploy)
        ```
    """
    from rich.console import Console, Group
    from rich.table import Table

    from prefect.runner import Runner

    runner = Runner(pause_on_shutdown=pause_on_shutdown, limit=limit, **kwargs)
    for deployment in args:
        await runner.add_deployment(deployment)

    if print_starting_message:
        help_message_top = (
            "[green]Your deployments are being served and polling for"
            " scheduled runs!\n[/]"
        )

        table = Table(title="Deployments", show_header=False)

        table.add_column(style="blue", no_wrap=True)

        for deployment in args:
            table.add_row(f"{deployment.flow_name}/{deployment.name}")

        help_message_bottom = (
            "\nTo trigger any of these deployments, use the"
            " following command:\n[blue]\n\t$ prefect deployment run"
            " [DEPLOYMENT_NAME]\n[/]"
        )
        if PREFECT_UI_URL:
            help_message_bottom += (
                "\nYou can also trigger your deployments via the Prefect UI:"
                f" [blue]{PREFECT_UI_URL.value()}/deployments[/]\n"
            )

        console = Console()
        console.print(
            Group(help_message_top, table, help_message_bottom), soft_wrap=True
        )

    await runner.start()

suspend_flow_run(wait_for_input=None, flow_run_id=None, timeout=3600, key=None, client=None) async

Suspends a flow run by stopping code execution until resumed.

When suspended, the flow run will continue execution until the NEXT task is orchestrated, at which point the flow will exit. Any tasks that have already started will run until completion. When resumed, the flow run will be rescheduled to finish execution. In order suspend a flow run in this way, the flow needs to have an associated deployment and results need to be configured with the persist_result option.

Parameters:

Name Type Description Default
flow_run_id Optional[UUID]

a flow run id. If supplied, this function will attempt to suspend the specified flow run. If not supplied will attempt to suspend the current flow run.

None
timeout Optional[int]

the number of seconds to wait for the flow to be resumed before failing. Defaults to 1 hour (3600 seconds). If the pause timeout exceeds any configured flow-level timeout, the flow might fail even after resuming.

3600
key Optional[str]

An optional key to prevent calling suspend more than once. This defaults to a random string and prevents suspends from running the same suspend twice. A custom key can be supplied for custom suspending behavior.

None
wait_for_input Optional[Type[T]]

a subclass of RunInput or any type supported by Pydantic. If provided when the flow suspends, the flow will remain suspended until receiving the input before resuming. If the flow is resumed without providing the input, the flow will fail. If the flow is resumed with the input, the flow will resume and the input will be loaded and returned from this function.

None
Source code in src/prefect/flow_runs.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
@sync_compatible
@inject_client
async def suspend_flow_run(
    wait_for_input: Optional[Type[T]] = None,
    flow_run_id: Optional[UUID] = None,
    timeout: Optional[int] = 3600,
    key: Optional[str] = None,
    client: PrefectClient = None,
) -> Optional[T]:
    """
    Suspends a flow run by stopping code execution until resumed.

    When suspended, the flow run will continue execution until the NEXT task is
    orchestrated, at which point the flow will exit. Any tasks that have
    already started will run until completion. When resumed, the flow run will
    be rescheduled to finish execution. In order suspend a flow run in this
    way, the flow needs to have an associated deployment and results need to be
    configured with the `persist_result` option.

    Args:
        flow_run_id: a flow run id. If supplied, this function will attempt to
            suspend the specified flow run. If not supplied will attempt to
            suspend the current flow run.
        timeout: the number of seconds to wait for the flow to be resumed before
            failing. Defaults to 1 hour (3600 seconds). If the pause timeout
            exceeds any configured flow-level timeout, the flow might fail even
            after resuming.
        key: An optional key to prevent calling suspend more than once. This
            defaults to a random string and prevents suspends from running the
            same suspend twice. A custom key can be supplied for custom
            suspending behavior.
        wait_for_input: a subclass of `RunInput` or any type supported by
            Pydantic. If provided when the flow suspends, the flow will remain
            suspended until receiving the input before resuming. If the flow is
            resumed without providing the input, the flow will fail. If the flow is
            resumed with the input, the flow will resume and the input will be
            loaded and returned from this function.
    """
    context = FlowRunContext.get()

    if flow_run_id is None:
        if TaskRunContext.get():
            raise RuntimeError("Cannot suspend task runs.")

        if context is None or context.flow_run is None:
            raise RuntimeError(
                "Flow runs can only be suspended from within a flow run."
            )

        logger = get_run_logger(context=context)
        logger.info(
            "Suspending flow run, execution will be rescheduled when this flow run is"
            " resumed."
        )
        flow_run_id = context.flow_run.id
        suspending_current_flow_run = True
        pause_counter = _observed_flow_pauses(context)
        pause_key = key or str(pause_counter)
    else:
        # Since we're suspending another flow run we need to generate a pause
        # key that won't conflict with whatever suspends/pauses that flow may
        # have. Since this method won't be called during that flow run it's
        # okay that this is non-deterministic.
        suspending_current_flow_run = False
        pause_key = key or str(uuid4())

    proposed_state = Suspended(timeout_seconds=timeout, pause_key=pause_key)

    if wait_for_input:
        wait_for_input = run_input_subclass_from_type(wait_for_input)
        run_input_keyset = keyset_from_paused_state(proposed_state)
        proposed_state.state_details.run_input_keyset = run_input_keyset

    try:
        state = await propose_state(
            client=client,
            state=proposed_state,
            flow_run_id=flow_run_id,
        )
    except Abort as exc:
        # Aborted requests mean the suspension is not allowed
        raise RuntimeError(f"Flow run cannot be suspended: {exc}")

    if state.is_running():
        # The orchestrator rejected the suspended state which means that this
        # suspend has happened before and the flow run has been resumed.
        if wait_for_input:
            # The flow run wanted input, so we need to load it and return it
            # to the user.
            return await wait_for_input.load(run_input_keyset)
        return

    if not state.is_paused():
        # If we receive anything but a PAUSED state, we are unable to continue
        raise RuntimeError(
            f"Flow run cannot be suspended. Received unexpected state from API: {state}"
        )

    if wait_for_input:
        await wait_for_input.save(run_input_keyset)

    if suspending_current_flow_run:
        # Exit this process so the run can be resubmitted later
        raise Pause()

tags(*new_tags)

Context manager to add tags to flow and task run calls.

Tags are always combined with any existing tags.

Yields:

Type Description
Set[str]

The current set of tags

Examples:

>>> from prefect import tags, task, flow
>>> @task
>>> def my_task():
>>>     pass

Run a task with tags

>>> @flow
>>> def my_flow():
>>>     with tags("a", "b"):
>>>         my_task()  # has tags: a, b

Run a flow with tags

>>> @flow
>>> def my_flow():
>>>     pass
>>> with tags("a", "b"):
>>>     my_flow()  # has tags: a, b

Run a task with nested tag contexts

>>> @flow
>>> def my_flow():
>>>     with tags("a", "b"):
>>>         with tags("c", "d"):
>>>             my_task()  # has tags: a, b, c, d
>>>         my_task()  # has tags: a, b

Inspect the current tags

>>> @flow
>>> def my_flow():
>>>     with tags("c", "d"):
>>>         with tags("e", "f") as current_tags:
>>>              print(current_tags)
>>> with tags("a", "b"):
>>>     my_flow()
{"a", "b", "c", "d", "e", "f"}
Source code in src/prefect/context.py
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
@contextmanager
def tags(*new_tags: str) -> Generator[Set[str], None, None]:
    """
    Context manager to add tags to flow and task run calls.

    Tags are always combined with any existing tags.

    Yields:
        The current set of tags

    Examples:
        >>> from prefect import tags, task, flow
        >>> @task
        >>> def my_task():
        >>>     pass

        Run a task with tags

        >>> @flow
        >>> def my_flow():
        >>>     with tags("a", "b"):
        >>>         my_task()  # has tags: a, b

        Run a flow with tags

        >>> @flow
        >>> def my_flow():
        >>>     pass
        >>> with tags("a", "b"):
        >>>     my_flow()  # has tags: a, b

        Run a task with nested tag contexts

        >>> @flow
        >>> def my_flow():
        >>>     with tags("a", "b"):
        >>>         with tags("c", "d"):
        >>>             my_task()  # has tags: a, b, c, d
        >>>         my_task()  # has tags: a, b

        Inspect the current tags

        >>> @flow
        >>> def my_flow():
        >>>     with tags("c", "d"):
        >>>         with tags("e", "f") as current_tags:
        >>>              print(current_tags)
        >>> with tags("a", "b"):
        >>>     my_flow()
        {"a", "b", "c", "d", "e", "f"}
    """
    current_tags = TagsContext.get().current_tags
    new_tags = current_tags.union(new_tags)
    with TagsContext(current_tags=new_tags):
        yield new_tags

task(__fn=None, *, name=None, description=None, tags=None, version=None, cache_policy=NotSet, cache_key_fn=None, cache_expiration=None, task_run_name=None, retries=None, retry_delay_seconds=None, retry_jitter_factor=None, persist_result=None, result_storage=None, result_storage_key=None, result_serializer=None, cache_result_in_memory=True, timeout_seconds=None, log_prints=None, refresh_cache=None, on_completion=None, on_failure=None, retry_condition_fn=None, viz_return_value=None)

Decorator to designate a function as a task in a Prefect workflow.

This decorator may be used for asynchronous or synchronous functions.

Parameters:

Name Type Description Default
name Optional[str]

An optional name for the task; if not provided, the name will be inferred from the given function.

None
description Optional[str]

An optional string description for the task.

None
tags Optional[Iterable[str]]

An optional set of tags to be associated with runs of this task. These tags are combined with any tags defined by a prefect.tags context at task runtime.

None
version Optional[str]

An optional string specifying the version of this task definition

None
cache_key_fn Callable[[TaskRunContext, Dict[str, Any]], Optional[str]]

An optional callable that, given the task run context and call parameters, generates a string key; if the key matches a previous completed state, that state result will be restored instead of running the task again.

None
cache_expiration Optional[timedelta]

An optional amount of time indicating how long cached states for this task should be restorable; if not provided, cached states will never expire.

None
task_run_name Optional[Union[Callable[[], str], str]]

An optional name to distinguish runs of this task; this name can be provided as a string template with the task's keyword arguments as variables, or a function that returns a string.

None
retries Optional[int]

An optional number of times to retry on task run failure

None
retry_delay_seconds Union[float, int, List[float], Callable[[int], List[float]], None]

Optionally configures how long to wait before retrying the task after failure. This is only applicable if retries is nonzero. This setting can either be a number of seconds, a list of retry delays, or a callable that, given the total number of retries, generates a list of retry delays. If a number of seconds, that delay will be applied to all retries. If a list, each retry will wait for the corresponding delay before retrying. When passing a callable or a list, the number of configured retry delays cannot exceed 50.

None
retry_jitter_factor Optional[float]

An optional factor that defines the factor to which a retry can be jittered in order to avoid a "thundering herd".

None
persist_result Optional[bool]

A toggle indicating whether the result of this task should be persisted to result storage. Defaults to None, which indicates that the global default should be used (which is True by default).

None
result_storage Optional[ResultStorage]

An optional block to use to persist the result of this task. Defaults to the value set in the flow the task is called in.

None
result_storage_key Optional[str]

An optional key to store the result in storage at when persisted. Defaults to a unique identifier.

None
result_serializer Optional[ResultSerializer]

An optional serializer to use to serialize the result of this task for persistence. Defaults to the value set in the flow the task is called in.

None
timeout_seconds Union[int, float, None]

An optional number of seconds indicating a maximum runtime for the task. If the task exceeds this runtime, it will be marked as failed.

None
log_prints Optional[bool]

If set, print statements in the task will be redirected to the Prefect logger for the task run. Defaults to None, which indicates that the value from the flow should be used.

None
refresh_cache Optional[bool]

If set, cached results for the cache key are not used. Defaults to None, which indicates that a cached result from a previous execution with matching cache key is used.

None
on_failure Optional[List[Callable[[Task, TaskRun, State], None]]]

An optional list of callables to run when the task enters a failed state.

None
on_completion Optional[List[Callable[[Task, TaskRun, State], None]]]

An optional list of callables to run when the task enters a completed state.

None
retry_condition_fn Optional[Callable[[Task, TaskRun, State], bool]]

An optional callable run when a task run returns a Failed state. Should return True if the task should continue to its retry policy (e.g. retries=3), and False if the task should end as failed. Defaults to None, indicating the task should always continue to its retry policy.

None
viz_return_value Any

An optional value to return when the task dependency tree is visualized.

None

Returns:

Type Description

A callable Task object which, when called, will submit the task for execution.

Examples:

Define a simple task

>>> @task
>>> def add(x, y):
>>>     return x + y

Define an async task

>>> @task
>>> async def add(x, y):
>>>     return x + y

Define a task with tags and a description

>>> @task(tags={"a", "b"}, description="This task is empty but its my first!")
>>> def my_task():
>>>     pass

Define a task with a custom name

>>> @task(name="The Ultimate Task")
>>> def my_task():
>>>     pass

Define a task that retries 3 times with a 5 second delay between attempts

>>> from random import randint
>>>
>>> @task(retries=3, retry_delay_seconds=5)
>>> def my_task():
>>>     x = randint(0, 5)
>>>     if x >= 3:  # Make a task that fails sometimes
>>>         raise ValueError("Retry me please!")
>>>     return x

Define a task that is cached for a day based on its inputs

>>> from prefect.tasks import task_input_hash
>>> from datetime import timedelta
>>>
>>> @task(cache_key_fn=task_input_hash, cache_expiration=timedelta(days=1))
>>> def my_task():
>>>     return "hello"
Source code in src/prefect/tasks.py
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
def task(
    __fn=None,
    *,
    name: Optional[str] = None,
    description: Optional[str] = None,
    tags: Optional[Iterable[str]] = None,
    version: Optional[str] = None,
    cache_policy: Union[CachePolicy, Type[NotSet]] = NotSet,
    cache_key_fn: Callable[["TaskRunContext", Dict[str, Any]], Optional[str]] = None,
    cache_expiration: Optional[datetime.timedelta] = None,
    task_run_name: Optional[Union[Callable[[], str], str]] = None,
    retries: Optional[int] = None,
    retry_delay_seconds: Union[
        float, int, List[float], Callable[[int], List[float]], None
    ] = None,
    retry_jitter_factor: Optional[float] = None,
    persist_result: Optional[bool] = None,
    result_storage: Optional[ResultStorage] = None,
    result_storage_key: Optional[str] = None,
    result_serializer: Optional[ResultSerializer] = None,
    cache_result_in_memory: bool = True,
    timeout_seconds: Union[int, float, None] = None,
    log_prints: Optional[bool] = None,
    refresh_cache: Optional[bool] = None,
    on_completion: Optional[List[Callable[["Task", TaskRun, State], None]]] = None,
    on_failure: Optional[List[Callable[["Task", TaskRun, State], None]]] = None,
    retry_condition_fn: Optional[Callable[["Task", TaskRun, State], bool]] = None,
    viz_return_value: Any = None,
):
    """
    Decorator to designate a function as a task in a Prefect workflow.

    This decorator may be used for asynchronous or synchronous functions.

    Args:
        name: An optional name for the task; if not provided, the name will be inferred
            from the given function.
        description: An optional string description for the task.
        tags: An optional set of tags to be associated with runs of this task. These
            tags are combined with any tags defined by a `prefect.tags` context at
            task runtime.
        version: An optional string specifying the version of this task definition
        cache_key_fn: An optional callable that, given the task run context and call
            parameters, generates a string key; if the key matches a previous completed
            state, that state result will be restored instead of running the task again.
        cache_expiration: An optional amount of time indicating how long cached states
            for this task should be restorable; if not provided, cached states will
            never expire.
        task_run_name: An optional name to distinguish runs of this task; this name can be provided
            as a string template with the task's keyword arguments as variables,
            or a function that returns a string.
        retries: An optional number of times to retry on task run failure
        retry_delay_seconds: Optionally configures how long to wait before retrying the
            task after failure. This is only applicable if `retries` is nonzero. This
            setting can either be a number of seconds, a list of retry delays, or a
            callable that, given the total number of retries, generates a list of retry
            delays. If a number of seconds, that delay will be applied to all retries.
            If a list, each retry will wait for the corresponding delay before retrying.
            When passing a callable or a list, the number of configured retry delays
            cannot exceed 50.
        retry_jitter_factor: An optional factor that defines the factor to which a retry
            can be jittered in order to avoid a "thundering herd".
        persist_result: A toggle indicating whether the result of this task
            should be persisted to result storage. Defaults to `None`, which
            indicates that the global default should be used (which is `True` by
            default).
        result_storage: An optional block to use to persist the result of this task.
            Defaults to the value set in the flow the task is called in.
        result_storage_key: An optional key to store the result in storage at when persisted.
            Defaults to a unique identifier.
        result_serializer: An optional serializer to use to serialize the result of this
            task for persistence. Defaults to the value set in the flow the task is
            called in.
        timeout_seconds: An optional number of seconds indicating a maximum runtime for
            the task. If the task exceeds this runtime, it will be marked as failed.
        log_prints: If set, `print` statements in the task will be redirected to the
            Prefect logger for the task run. Defaults to `None`, which indicates
            that the value from the flow should be used.
        refresh_cache: If set, cached results for the cache key are not used.
            Defaults to `None`, which indicates that a cached result from a previous
            execution with matching cache key is used.
        on_failure: An optional list of callables to run when the task enters a failed state.
        on_completion: An optional list of callables to run when the task enters a completed state.
        retry_condition_fn: An optional callable run when a task run returns a Failed state. Should
            return `True` if the task should continue to its retry policy (e.g. `retries=3`), and `False` if the task
            should end as failed. Defaults to `None`, indicating the task should always continue
            to its retry policy.
        viz_return_value: An optional value to return when the task dependency tree is visualized.

    Returns:
        A callable `Task` object which, when called, will submit the task for execution.

    Examples:
        Define a simple task

        >>> @task
        >>> def add(x, y):
        >>>     return x + y

        Define an async task

        >>> @task
        >>> async def add(x, y):
        >>>     return x + y

        Define a task with tags and a description

        >>> @task(tags={"a", "b"}, description="This task is empty but its my first!")
        >>> def my_task():
        >>>     pass

        Define a task with a custom name

        >>> @task(name="The Ultimate Task")
        >>> def my_task():
        >>>     pass

        Define a task that retries 3 times with a 5 second delay between attempts

        >>> from random import randint
        >>>
        >>> @task(retries=3, retry_delay_seconds=5)
        >>> def my_task():
        >>>     x = randint(0, 5)
        >>>     if x >= 3:  # Make a task that fails sometimes
        >>>         raise ValueError("Retry me please!")
        >>>     return x

        Define a task that is cached for a day based on its inputs

        >>> from prefect.tasks import task_input_hash
        >>> from datetime import timedelta
        >>>
        >>> @task(cache_key_fn=task_input_hash, cache_expiration=timedelta(days=1))
        >>> def my_task():
        >>>     return "hello"
    """

    if __fn:
        if isinstance(__fn, (classmethod, staticmethod)):
            method_decorator = type(__fn).__name__
            raise TypeError(f"@{method_decorator} should be applied on top of @task")
        return cast(
            Task[P, R],
            Task(
                fn=__fn,
                name=name,
                description=description,
                tags=tags,
                version=version,
                cache_policy=cache_policy,
                cache_key_fn=cache_key_fn,
                cache_expiration=cache_expiration,
                task_run_name=task_run_name,
                retries=retries,
                retry_delay_seconds=retry_delay_seconds,
                retry_jitter_factor=retry_jitter_factor,
                persist_result=persist_result,
                result_storage=result_storage,
                result_storage_key=result_storage_key,
                result_serializer=result_serializer,
                cache_result_in_memory=cache_result_in_memory,
                timeout_seconds=timeout_seconds,
                log_prints=log_prints,
                refresh_cache=refresh_cache,
                on_completion=on_completion,
                on_failure=on_failure,
                retry_condition_fn=retry_condition_fn,
                viz_return_value=viz_return_value,
            ),
        )
    else:
        return cast(
            Callable[[Callable[P, R]], Task[P, R]],
            partial(
                task,
                name=name,
                description=description,
                tags=tags,
                version=version,
                cache_policy=cache_policy,
                cache_key_fn=cache_key_fn,
                cache_expiration=cache_expiration,
                task_run_name=task_run_name,
                retries=retries,
                retry_delay_seconds=retry_delay_seconds,
                retry_jitter_factor=retry_jitter_factor,
                persist_result=persist_result,
                result_storage=result_storage,
                result_storage_key=result_storage_key,
                result_serializer=result_serializer,
                cache_result_in_memory=cache_result_in_memory,
                timeout_seconds=timeout_seconds,
                log_prints=log_prints,
                refresh_cache=refresh_cache,
                on_completion=on_completion,
                on_failure=on_failure,
                retry_condition_fn=retry_condition_fn,
                viz_return_value=viz_return_value,
            ),
        )