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[Union[ResultStorage, str]]

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
 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
 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
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
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
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[Union[ResultStorage, str]] = 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")

        self.name = name or fn.__name__.replace("_", "-").replace(
            "<lambda>",
            "unknown-lambda",  # prefect API will not accept "<" or ">" in flow names
        )
        _raise_on_name_with_banned_characters(self.name)

        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 = asyncio.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

        # result persistence settings
        if persist_result is None:
            if result_storage is not None or result_serializer is not None:
                persist_result = True

        self.persist_result = persist_result
        if result_storage and not isinstance(result_storage, str):
            if getattr(result_storage, "_block_document_id", None) is None:
                raise TypeError(
                    "Result storage configuration must be persisted server-side."
                    " Please call `.save()` on your block before passing it in."
                )
        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
        """

        def resolve_block_reference(data: Any) -> Any:
            if isinstance(data, dict) and "$ref" in data:
                return Block.load_from_ref(data["$ref"], _sync=True)
            return data

        try:
            parameters = visit_collection(
                parameters, resolve_block_reference, return_data=True
            )
        except (ValueError, RuntimeError) as exc:
            raise ParameterTypeError(
                "Failed to resolve block references in parameters."
            ) from exc

        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(iter(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
            if isinstance(value, (PrefectFuture, State)):
                # Don't call jsonable_encoder() on a PrefectFuture or State to
                # avoid triggering a __getitem__ call
                serialized_parameters[key] = f"<{type(value).__name__}>"
                continue
            try:
                serialized_parameters[key] = jsonable_encoder(value)
            except (TypeError, ValueError):
                logger.debug(
                    f"Parameter {key!r} for flow {self.name!r} is 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
    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["FlexibleScheduleList"] = None,
        concurrency_limit: Optional[Union[int, ConcurrencyLimitConfig, None]] = 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`.
            concurrency_limit: The maximum number of runs of this deployment that can run at the same time.
            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,
                flow_name=self.name,
                interval=interval,
                cron=cron,
                rrule=rrule,
                paused=paused,
                schedules=schedules,
                concurrency_limit=concurrency_limit,
                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,
            )  # type: ignore # TODO: remove sync_compatible
        else:
            return RunnerDeployment.from_flow(
                flow=self,
                name=name,
                interval=interval,
                cron=cron,
                rrule=rrule,
                paused=paused,
                schedules=schedules,
                concurrency_limit=concurrency_limit,
                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

    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["FlexibleScheduleList"] = None,
        global_limit: Optional[Union[int, ConcurrencyLimitConfig, None]] = 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`.
            global_limit: The maximum number of concurrent runs allowed across all served flow instances associated with the same deployment.
            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 by the created runner; only applies to this served flow. To apply a limit across multiple served flows, use `global_limit`.
            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 = runner.add_flow(
            self,
            name=name,
            triggers=triggers,
            interval=interval,
            cron=cron,
            rrule=rrule,
            paused=paused,
            schedules=schedules,
            concurrency_limit=global_limit,
            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)

        try:
            loop = asyncio.get_running_loop()
        except RuntimeError as exc:
            if "no running event loop" in str(exc):
                loop = None
            else:
                raise

        try:
            if loop is not None:
                loop.run_until_complete(runner.start(webserver=webserver))
            else:
                asyncio.run(runner.start(webserver=webserver))
        except (KeyboardInterrupt, TerminationSignal) as exc:
            logger.info(f"Received {type(exc).__name__}, shutting down...")
            if loop is not None:
                loop.stop()

    @classmethod
    @sync_compatible
    async def from_source(
        cls: Type["Flow[P, R]"],
        source: Union[str, "RunnerStorage", ReadableDeploymentStorage],
        entrypoint: str,
    ) -> "Flow[P, R]":
        """
        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()
            ```

            Load a flow from a local directory:

            ``` python
            # from_local_source.py

            from pathlib import Path
            from prefect import flow

            @flow(log_prints=True)
            def my_flow(name: str = "world"):
                print(f"Hello {name}! I'm a flow from a Python script!")

            if __name__ == "__main__":
                my_flow.from_source(
                    source=str(Path(__file__).parent),
                    entrypoint="from_local_source.py:my_flow",
                ).deploy(
                    name="my-deployment",
                    parameters=dict(name="Marvin"),
                    work_pool_name="local",
                )
            ```
        """

        from prefect.runner.storage import (
            BlockStorageAdapter,
            LocalStorage,
            RunnerStorage,
            create_storage_from_source,
        )

        if isinstance(source, (Path, str)):
            if isinstance(source, Path):
                source = str(source)
            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()

            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,
        concurrency_limit: Optional[Union[int, ConcurrencyLimitConfig, None]] = 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`.
            concurrency_limit: The maximum number of runs that can be executed concurrently.
            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",
                )
            ```
        """
        if not (
            work_pool_name := work_pool_name or PREFECT_DEFAULT_WORK_POOL_NAME.value()
        ):
            raise ValueError(
                "No work pool name provided. Please provide a `work_pool_name` or set the"
                " `PREFECT_DEFAULT_WORK_POOL_NAME` environment variable."
            )

        from prefect.client.orchestration import get_client

        try:
            async with get_client() as client:
                work_pool = await client.read_work_pool(work_pool_name)
                active_workers = await client.read_workers_for_work_pool(
                    work_pool_name,
                    worker_filter=WorkerFilter(status={"any_": ["ONLINE"]}),
                )
        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,
            concurrency_limit=concurrency_limit,
            paused=paused,
            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,
        )

        from prefect.deployments.runner import deploy

        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
                and not active_workers
            ):
                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
    ) -> Coroutine[Any, Any, T]:
        ...

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

    @overload
    def __call__(
        self: "Flow[P, Coroutine[Any, Any, T]]",
        *args: P.args,
        return_state: Literal[True],
        **kwargs: P.kwargs,
    ) -> Awaitable[State[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_TESTING_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)

__call__(*args: P.args, **kwargs: P.kwargs) -> None
__call__(*args: P.args, **kwargs: P.kwargs) -> Coroutine[Any, Any, T]
__call__(*args: P.args, **kwargs: P.kwargs) -> T
__call__(*args: P.args, return_state: Literal[True], **kwargs: P.kwargs) -> Awaitable[State[T]]
__call__(*args: P.args, return_state: Literal[True], **kwargs: P.kwargs) -> State[T]

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
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
1354
1355
1356
1357
1358
1359
1360
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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, concurrency_limit=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
concurrency_limit Optional[Union[int, ConcurrencyLimitConfig, None]]

The maximum number of runs that can be executed concurrently.

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
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
@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,
    concurrency_limit: Optional[Union[int, ConcurrencyLimitConfig, None]] = 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`.
        concurrency_limit: The maximum number of runs that can be executed concurrently.
        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",
            )
        ```
    """
    if not (
        work_pool_name := work_pool_name or PREFECT_DEFAULT_WORK_POOL_NAME.value()
    ):
        raise ValueError(
            "No work pool name provided. Please provide a `work_pool_name` or set the"
            " `PREFECT_DEFAULT_WORK_POOL_NAME` environment variable."
        )

    from prefect.client.orchestration import get_client

    try:
        async with get_client() as client:
            work_pool = await client.read_work_pool(work_pool_name)
            active_workers = await client.read_workers_for_work_pool(
                work_pool_name,
                worker_filter=WorkerFilter(status={"any_": ["ONLINE"]}),
            )
    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,
        concurrency_limit=concurrency_limit,
        paused=paused,
        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,
    )

    from prefect.deployments.runner import deploy

    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
            and not active_workers
        ):
            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
Flow[P, R]

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()

Load a flow from a local directory:

# from_local_source.py

from pathlib import Path
from prefect import flow

@flow(log_prints=True)
def my_flow(name: str = "world"):
    print(f"Hello {name}! I'm a flow from a Python script!")

if __name__ == "__main__":
    my_flow.from_source(
        source=str(Path(__file__).parent),
        entrypoint="from_local_source.py:my_flow",
    ).deploy(
        name="my-deployment",
        parameters=dict(name="Marvin"),
        work_pool_name="local",
    )
Source code in src/prefect/flows.py
 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
@classmethod
@sync_compatible
async def from_source(
    cls: Type["Flow[P, R]"],
    source: Union[str, "RunnerStorage", ReadableDeploymentStorage],
    entrypoint: str,
) -> "Flow[P, R]":
    """
    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()
        ```

        Load a flow from a local directory:

        ``` python
        # from_local_source.py

        from pathlib import Path
        from prefect import flow

        @flow(log_prints=True)
        def my_flow(name: str = "world"):
            print(f"Hello {name}! I'm a flow from a Python script!")

        if __name__ == "__main__":
            my_flow.from_source(
                source=str(Path(__file__).parent),
                entrypoint="from_local_source.py:my_flow",
            ).deploy(
                name="my-deployment",
                parameters=dict(name="Marvin"),
                work_pool_name="local",
            )
        ```
    """

    from prefect.runner.storage import (
        BlockStorageAdapter,
        LocalStorage,
        RunnerStorage,
        create_storage_from_source,
    )

    if isinstance(source, (Path, str)):
        if isinstance(source, Path):
            source = str(source)
        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()

        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
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
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
        if isinstance(value, (PrefectFuture, State)):
            # Don't call jsonable_encoder() on a PrefectFuture or State to
            # avoid triggering a __getitem__ call
            serialized_parameters[key] = f"<{type(value).__name__}>"
            continue
        try:
            serialized_parameters[key] = jsonable_encoder(value)
        except (TypeError, ValueError):
            logger.debug(
                f"Parameter {key!r} for flow {self.name!r} is 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, global_limit=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)

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[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
global_limit Optional[Union[int, ConcurrencyLimitConfig, None]]

The maximum number of concurrent runs allowed across all served flow instances associated with the same deployment.

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 by the created runner; only applies to this served flow. To apply a limit across multiple served flows, use global_limit.

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
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
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["FlexibleScheduleList"] = None,
    global_limit: Optional[Union[int, ConcurrencyLimitConfig, None]] = 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`.
        global_limit: The maximum number of concurrent runs allowed across all served flow instances associated with the same deployment.
        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 by the created runner; only applies to this served flow. To apply a limit across multiple served flows, use `global_limit`.
        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 = runner.add_flow(
        self,
        name=name,
        triggers=triggers,
        interval=interval,
        cron=cron,
        rrule=rrule,
        paused=paused,
        schedules=schedules,
        concurrency_limit=global_limit,
        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)

    try:
        loop = asyncio.get_running_loop()
    except RuntimeError as exc:
        if "no running event loop" in str(exc):
            loop = None
        else:
            raise

    try:
        if loop is not None:
            loop.run_until_complete(runner.start(webserver=webserver))
        else:
            asyncio.run(runner.start(webserver=webserver))
    except (KeyboardInterrupt, TerminationSignal) as exc:
        logger.info(f"Received {type(exc).__name__}, shutting down...")
        if loop is not None:
            loop.stop()

to_deployment(name, interval=None, cron=None, rrule=None, paused=None, schedules=None, concurrency_limit=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[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
concurrency_limit Optional[Union[int, ConcurrencyLimitConfig, None]]

The maximum number of runs of this deployment that can run at the same time.

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
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
@sync_compatible
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["FlexibleScheduleList"] = None,
    concurrency_limit: Optional[Union[int, ConcurrencyLimitConfig, None]] = 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`.
        concurrency_limit: The maximum number of runs of this deployment that can run at the same time.
        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,
            flow_name=self.name,
            interval=interval,
            cron=cron,
            rrule=rrule,
            paused=paused,
            schedules=schedules,
            concurrency_limit=concurrency_limit,
            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,
        )  # type: ignore # TODO: remove sync_compatible
    else:
        return RunnerDeployment.from_flow(
            flow=self,
            name=name,
            interval=interval,
            cron=cron,
            rrule=rrule,
            paused=paused,
            schedules=schedules,
            concurrency_limit=concurrency_limit,
            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
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
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
    """

    def resolve_block_reference(data: Any) -> Any:
        if isinstance(data, dict) and "$ref" in data:
            return Block.load_from_ref(data["$ref"], _sync=True)
        return data

    try:
        parameters = visit_collection(
            parameters, resolve_block_reference, return_data=True
        )
    except (ValueError, RuntimeError) as exc:
        raise ParameterTypeError(
            "Failed to resolve block references in parameters."
        ) from exc

    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(iter(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
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
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
@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_TESTING_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
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
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

State

Bases: ObjectBaseModel, Generic[R]

The state of a run.

Source code in src/prefect/client/schemas/objects.py
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
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: Annotated[
        Union[
            Annotated["BaseResult[R]", Tag("BaseResult")],
            Annotated["ResultRecordMetadata", Tag("ResultRecordMetadata")],
            Annotated[Any, Tag("Any")],
        ],
        Discriminator(data_discriminator),
    ] = 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]:
        ...

    @deprecated.deprecated_parameter(
        "fetch",
        when=lambda fetch: fetch is not True,
        start_date="Oct 2024",
        end_date="Jan 2025",
        help="Please ensure you are awaiting the call to `result()` when calling in an async context.",
    )
    def result(
        self,
        raise_on_failure: bool = True,
        fetch: bool = True,
        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. When flow
                was run in a different memory space (using `run_deployment`), this will only raise
                if `fetch` is `True`.
            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:
            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

            Get the result with `raise_on_failure` from a flow run in a different memory space

            >>> @flow
            >>> async def my_flow():
            >>>     raise ValueError("oh no!")
            >>> my_flow.deploy("my_deployment/my_flow")
            >>> flow_run = run_deployment("my_deployment/my_flow")
            >>> await flow_run.state.result(raise_on_failure=True) # Raises `ValueError("oh no!")`
        """
        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,
            ResultRecord,
            should_persist_result,
        )

        if isinstance(self.data, BaseResult):
            data = self.data
        elif isinstance(self.data, ResultRecord) and should_persist_result():
            data = self.data.metadata
        else:
            data = None

        return StateCreate(
            type=self.type,
            name=self.name,
            message=self.message,
            data=data,
            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

    @model_validator(mode="after")
    def set_unpersisted_results_to_none(self) -> Self:
        if isinstance(self.data, dict) and self.data.get("type") == "unpersisted":
            self.data = None
        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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
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
343
344
345
346
347
348
349
350
351
@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
407
408
409
410
411
412
413
414
415
416
417
418
419
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
396
397
398
399
400
401
402
403
404
405
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=True, retry_result_failure=True)

result(raise_on_failure: bool = True) -> R
result(raise_on_failure: bool = False) -> Union[R, Exception]

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. When flow was run in a different memory space (using run_deployment), this will only raise if fetch is True.

True
fetch 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.

True
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:

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

Get the result with raise_on_failure from a flow run in a different memory space

>>> @flow
>>> async def my_flow():
>>>     raise ValueError("oh no!")
>>> my_flow.deploy("my_deployment/my_flow")
>>> flow_run = run_deployment("my_deployment/my_flow")
>>> await flow_run.state.result(raise_on_failure=True) # Raises `ValueError("oh no!")`
Source code in src/prefect/client/schemas/objects.py
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
@deprecated.deprecated_parameter(
    "fetch",
    when=lambda fetch: fetch is not True,
    start_date="Oct 2024",
    end_date="Jan 2025",
    help="Please ensure you are awaiting the call to `result()` when calling in an async context.",
)
def result(
    self,
    raise_on_failure: bool = True,
    fetch: bool = True,
    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. When flow
            was run in a different memory space (using `run_deployment`), this will only raise
            if `fetch` is `True`.
        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:
        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

        Get the result with `raise_on_failure` from a flow run in a different memory space

        >>> @flow
        >>> async def my_flow():
        >>>     raise ValueError("oh no!")
        >>> my_flow.deploy("my_deployment/my_flow")
        >>> flow_run = run_deployment("my_deployment/my_flow")
        >>> await flow_run.state.result(raise_on_failure=True) # Raises `ValueError("oh no!")`
    """
    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
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
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,
        ResultRecord,
        should_persist_result,
    )

    if isinstance(self.data, BaseResult):
        data = self.data
    elif isinstance(self.data, ResultRecord) and should_persist_result():
        data = self.data.metadata
    else:
        data = None

    return StateCreate(
        type=self.type,
        name=self.name,
        message=self.message,
        data=data,
        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 Union[CachePolicy, Type[NotSet]]

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], Callable[[Dict[str, Any]], 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
 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
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
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
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: Union[CachePolicy, Type[NotSet]] = 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], Callable[[Dict[str, Any]], 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 = asyncio.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 [])

        self.task_key = _generate_task_key(self.fn)

        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

        # result persistence settings
        if persist_result is None:
            if any(
                [
                    cache_policy and cache_policy != NONE and cache_policy != NotSet,
                    cache_key_fn is not None,
                    result_storage_key is not None,
                    result_storage is not None,
                    result_serializer is not None,
                ]
            ):
                persist_result = True

        if persist_result is False:
            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

        if result_storage and not isinstance(result_storage, str):
            if getattr(result_storage, "_block_document_id", None) is None:
                raise TypeError(
                    "Result storage configuration must be persisted server-side."
                    " Please call `.save()` on your block before passing it in."
                )

        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], Callable[[Dict[str, Any]], str], str, Type[NotSet]]
        ] = NotSet,
        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
            if task_run_name is not NotSet
            else self.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

                store = await ResultStore(
                    result_storage=await get_or_create_default_task_scheduling_storage()
                ).update_for_task(self)
                context = serialize_context()
                data: Dict[str, Any] = {"context": context}
                if parameters:
                    data["parameters"] = parameters
                if wait_for:
                    data["wait_for"] = wait_for
                await store.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

    async def create_local_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, stable=False
                )
                task_run_name = f"{self.name}-{dynamic_key[:3]}"

            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

                store = await ResultStore(
                    result_storage=await get_or_create_default_task_scheduling_storage()
                ).update_for_task(task)
                context = serialize_context()
                data: Dict[str, Any] = {"context": context}
                if parameters:
                    data["parameters"] = parameters
                if wait_for:
                    data["wait_for"] = wait_for
                await store.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)

            flow_run_id = (
                getattr(flow_run_context.flow_run, "id", None)
                if flow_run_context and flow_run_context.flow_run
                else None
            )
            task_run_id = id or uuid4()
            state = prefect.states.Pending(
                state_details=StateDetails(
                    task_run_id=task_run_id,
                    flow_run_id=flow_run_id,
                )
            )
            task_run = TaskRun(
                id=task_run_id,
                name=task_run_name,
                flow_run_id=flow_run_id,
                task_key=self.task_key,
                dynamic_key=str(dynamic_key),
                task_version=self.version,
                empirical_policy=TaskRunPolicy(
                    retries=self.retries,
                    retry_delay=self.retry_delay_seconds,
                    retry_jitter_factor=self.retry_jitter_factor,
                ),
                tags=list(set(self.tags).union(TagsContext.get().current_tags or [])),
                task_inputs=task_inputs or {},
                expected_start_time=state.timestamp,
                state_id=state.id,
                state_type=state.type,
                state_name=state.name,
                state=state,
                created=state.timestamp,
                updated=state.timestamp,
            )

            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]:
        ...

    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.

        This method is always synchronous, even if the underlying user function is asynchronous.

        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():
            >>>     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, R]",
        *args: Any,
        return_state: Literal[True],
        wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = ...,
        deferred: bool = ...,
        **kwargs: Any,
    ) -> List[State[R]]:
        ...

    @overload
    def map(
        self: "Task[P, R]",
        *args: Any,
        wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = ...,
        deferred: bool = ...,
        **kwargs: Any,
    ) -> PrefectFutureList[R]:
        ...

    @overload
    def map(
        self: "Task[P, R]",
        *args: Any,
        return_state: Literal[True],
        wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = ...,
        deferred: bool = ...,
        **kwargs: Any,
    ) -> List[State[R]]:
        ...

    @overload
    def map(
        self: "Task[P, R]",
        *args: Any,
        wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = ...,
        deferred: bool = ...,
        **kwargs: Any,
    ) -> PrefectFutureList[R]:
        ...

    @overload
    def map(
        self: "Task[P, Coroutine[Any, Any, R]]",
        *args: Any,
        return_state: Literal[True],
        wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = ...,
        deferred: bool = ...,
        **kwargs: Any,
    ) -> List[State[R]]:
        ...

    @overload
    def map(
        self: "Task[P, Coroutine[Any, Any, R]]",
        *args: Any,
        return_state: Literal[False],
        wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = ...,
        deferred: bool = ...,
        **kwargs: Any,
    ) -> PrefectFutureList[R]:
        ...

    def map(
        self,
        *args: Any,
        return_state: bool = False,
        wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = 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.

        This method is always synchronous, even if the underlying user function is asynchronous.

        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: TaskRun = run_coro_as_sync(
            self.create_run(
                parameters=parameters,
                deferred=True,
                wait_for=wait_for,
                extra_task_inputs=dependencies,
            )
        )  # type: ignore

        from prefect.utilities.engine import emit_task_run_state_change_event

        # emit a `SCHEDULED` event for the task run
        emit_task_run_state_change_event(
            task_run=task_run,
            initial_state=None,
            validated_state=task_run.state,
        )

        if task_run_url := url_for(task_run):
            logger.info(
                f"Created task run {task_run.name!r}. View it in the UI at {task_run_url!r}"
            )

        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 task runner 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)

__call__(*args: P.args, **kwargs: P.kwargs) -> None
__call__(*args: P.args, **kwargs: P.kwargs) -> T
__call__(*args: P.args, return_state: Literal[True], **kwargs: P.kwargs) -> State[T]

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
 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
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
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
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
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: TaskRun = run_coro_as_sync(
        self.create_run(
            parameters=parameters,
            deferred=True,
            wait_for=wait_for,
            extra_task_inputs=dependencies,
        )
    )  # type: ignore

    from prefect.utilities.engine import emit_task_run_state_change_event

    # emit a `SCHEDULED` event for the task run
    emit_task_run_state_change_event(
        task_run=task_run,
        initial_state=None,
        validated_state=task_run.state,
    )

    if task_run_url := url_for(task_run):
        logger.info(
            f"Created task run {task_run.name!r}. View it in the UI at {task_run_url!r}"
        )

    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
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
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)

map(*args: Any, return_state: Literal[True], wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = ..., deferred: bool = ..., **kwargs: Any) -> List[State[R]]
map(*args: Any, wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = ..., deferred: bool = ..., **kwargs: Any) -> PrefectFutureList[R]
map(*args: Any, return_state: Literal[True], wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = ..., deferred: bool = ..., **kwargs: Any) -> List[State[R]]
map(*args: Any, wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = ..., deferred: bool = ..., **kwargs: Any) -> PrefectFutureList[R]
map(*args: Any, return_state: Literal[True], wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = ..., deferred: bool = ..., **kwargs: Any) -> List[State[R]]
map(*args: Any, return_state: Literal[False], wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = ..., deferred: bool = ..., **kwargs: Any) -> PrefectFutureList[R]

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.

This method is always synchronous, even if the underlying user function is asynchronous.

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[Union[PrefectFuture[T], T]]]

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
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
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
def map(
    self,
    *args: Any,
    return_state: bool = False,
    wait_for: Optional[Iterable[Union[PrefectFuture[T], T]]] = 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.

    This method is always synchronous, even if the underlying user function is asynchronous.

    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 task runner 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
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
@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 task runner 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(*args: P.args, **kwargs: P.kwargs) -> PrefectFuture[NoReturn]
submit(*args: P.args, **kwargs: P.kwargs) -> PrefectFuture[T]
submit(*args: P.args, **kwargs: P.kwargs) -> PrefectFuture[T]
submit(*args: P.args, return_state: Literal[True], **kwargs: P.kwargs) -> State[T]
submit(*args: P.args, return_state: Literal[True], **kwargs: P.kwargs) -> State[T]

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.

This method is always synchronous, even if the underlying user function is asynchronous.

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():
>>>     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
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
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.

    This method is always synchronous, even if the underlying user function is asynchronous.

    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():
        >>>     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=NotSet, 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], Callable[[Dict[str, Any]], str], str, Type[NotSet]]]

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.

NotSet
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
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
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], Callable[[Dict[str, Any]], str], str, Type[NotSet]]
    ] = NotSet,
    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
        if task_run_name is not NotSet
        else self.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
 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
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
class Transaction(ContextModel):
    """
    A base model for transaction state.
    """

    store: Union[RecordStore, ResultStore, None] = None
    key: Optional[str] = None
    children: List["Transaction"] = Field(default_factory=list)
    commit_mode: Optional[CommitMode] = None
    isolation_level: Optional[IsolationLevel] = IsolationLevel.READ_COMMITTED
    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] = Field(
        default_factory=partial(get_logger, "transactions")
    )
    write_on_commit: bool = True
    _stored_values: Dict[str, Any] = PrivateAttr(default_factory=dict)
    _staged_value: Any = None
    __var__: ContextVar = ContextVar("transaction")

    def set(self, name: str, value: Any) -> None:
        """
        Set a stored value in the transaction.

        Args:
            name: The name of the value to set
            value: The value to set

        Examples:
            Set a value for use later in the transaction:
            ```python
            with transaction() as txn:
                txn.set("key", "value")
                ...
                assert txn.get("key") == "value"
            ```
        """
        self._stored_values[name] = value

    def get(self, name: str, default: Any = NotSet) -> Any:
        """
        Get a stored value from the transaction.

        Child transactions will return values from their parents unless a value with
        the same name is set in the child transaction.

        Direct changes to returned values will not update the stored value. To update the
        stored value, use the `set` method.

        Args:
            name: The name of the value to get
            default: The default value to return if the value is not found

        Returns:
            The value from the transaction

        Examples:
            Get a value from the transaction:
            ```python
            with transaction() as txn:
                txn.set("key", "value")
                ...
                assert txn.get("key") == "value"
            ```

            Get a value from a parent transaction:
            ```python
            with transaction() as parent:
                parent.set("key", "parent_value")
                with transaction() as child:
                    assert child.get("key") == "parent_value"
            ```

            Update a stored value:
            ```python
            with transaction() as txn:
                txn.set("key", [1, 2, 3])
                value = txn.get("key")
                value.append(4)
                # Stored value is not updated until `.set` is called
                assert value == [1, 2, 3, 4]
                assert txn.get("key") == [1, 2, 3]

                txn.set("key", value)
                assert txn.get("key") == [1, 2, 3, 4]
            ```
        """
        # deepcopy to prevent mutation of stored values
        value = copy.deepcopy(self._stored_values.get(name, NotSet))
        if value is NotSet:
            # if there's a parent transaction, get the value from the parent
            parent = self.get_parent()
            if parent is not None:
                value = parent.get(name, default)
            # if there's no parent transaction, use the default
            elif default is not NotSet:
                value = default
            else:
                raise ValueError(f"Could not retrieve value for unknown key: {name}")
        return value

    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."
            )
        parent = get_transaction()
        # set default commit behavior; either inherit from parent or set a default of eager
        if self.commit_mode is None:
            self.commit_mode = parent.commit_mode if parent else CommitMode.LAZY
        # set default isolation level; either inherit from parent or set a default of read committed
        if self.isolation_level is None:
            self.isolation_level = (
                parent.isolation_level if parent else IsolationLevel.READ_COMMITTED
            )

        assert self.isolation_level is not None, "Isolation level was not set correctly"
        if (
            self.store
            and self.key
            and not self.store.supports_isolation_level(self.isolation_level)
        ):
            raise ConfigurationError(
                f"Isolation level {self.isolation_level.name} is not supported by provided "
                "configuration. Please ensure you've provided a lock file directory or lock "
                "manager when using the SERIALIZABLE isolation level."
            )

        # 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):
        if (
            self.store
            and self.key
            and self.isolation_level == IsolationLevel.SERIALIZABLE
        ):
            self.logger.debug(f"Acquiring lock for transaction {self.key!r}")
            self.store.acquire_lock(self.key)
        if (
            not self.overwrite
            and self.store
            and self.key
            and self.store.exists(key=self.key)
        ):
            self.state = TransactionState.COMMITTED

    def read(self) -> Union["BaseResult", ResultRecord, None]:
        if self.store and self.key:
            record = self.store.read(key=self.key)
            if isinstance(record, ResultRecord):
                return record
            # for backwards compatibility, if we encounter a transaction record, return the result
            # This happens when the transaction is using a `ResultStore`
            if isinstance(record, TransactionRecord):
                return record.result
        return None

    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"]:
        parent = None
        if self._token:
            prev_var = getattr(self._token, "old_value")
            if prev_var != Token.MISSING:
                parent = prev_var
        else:
            # `_token` has been reset so we need to get the active transaction from the context var
            parent = self.get_active()
        return parent

    def commit(self) -> bool:
        if self.state in [TransactionState.ROLLED_BACK, TransactionState.COMMITTED]:
            if (
                self.store
                and self.key
                and self.isolation_level == IsolationLevel.SERIALIZABLE
            ):
                self.logger.debug(f"Releasing lock for transaction {self.key!r}")
                self.store.release_lock(self.key)

            return False

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

            for hook in self.on_commit_hooks:
                self.run_hook(hook, "commit")

            if self.store and self.key and self.write_on_commit:
                if isinstance(self.store, ResultStore):
                    if isinstance(self._staged_value, BaseResult):
                        self.store.write(
                            key=self.key, obj=self._staged_value.get(_sync=True)
                        )
                    elif isinstance(self._staged_value, ResultRecord):
                        self.store.persist_result_record(
                            result_record=self._staged_value
                        )
                    else:
                        self.store.write(key=self.key, obj=self._staged_value)
                else:
                    self.store.write(key=self.key, result=self._staged_value)

            self.state = TransactionState.COMMITTED
            if (
                self.store
                and self.key
                and self.isolation_level == IsolationLevel.SERIALIZABLE
            ):
                self.logger.debug(f"Releasing lock for transaction {self.key!r}")
                self.store.release_lock(self.key)
            return True
        except SerializationError as exc:
            if self.logger:
                self.logger.warning(
                    f"Encountered an error while serializing result for transaction {self.key!r}: {exc}"
                    " Code execution will continue, but the transaction will not be committed.",
                )
            self.rollback()
            return False
        except Exception:
            if self.logger:
                self.logger.exception(
                    f"An error was encountered while committing transaction {self.key!r}",
                    exc_info=True,
                )
            self.rollback()
            return False

    def run_hook(self, hook, hook_type: str) -> None:
        hook_name = _get_hook_name(hook)
        # Undocumented way to disable logging for a hook. Subject to change.
        should_log = getattr(hook, "log_on_run", True)

        if should_log:
            self.logger.info(f"Running {hook_type} hook {hook_name!r}")

        try:
            hook(self)
        except Exception as exc:
            if should_log:
                self.logger.error(
                    f"An error was encountered while running {hook_type} hook {hook_name!r}",
                )
            raise exc
        else:
            if should_log:
                self.logger.info(
                    f"{hook_type.capitalize()} hook {hook_name!r} finished running successfully"
                )

    def stage(
        self,
        value: Any,
        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):
                self.run_hook(hook, "rollback")

            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 rolling back transaction {self.key!r}",
                    exc_info=True,
                )
            return False
        finally:
            if (
                self.store
                and self.key
                and self.isolation_level == IsolationLevel.SERIALIZABLE
            ):
                self.logger.debug(f"Releasing lock for transaction {self.key!r}")
                self.store.release_lock(self.key)

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

get(name, default=NotSet)

Get a stored value from the transaction.

Child transactions will return values from their parents unless a value with the same name is set in the child transaction.

Direct changes to returned values will not update the stored value. To update the stored value, use the set method.

Parameters:

Name Type Description Default
name str

The name of the value to get

required
default Any

The default value to return if the value is not found

NotSet

Returns:

Type Description
Any

The value from the transaction

Examples:

Get a value from the transaction:

with transaction() as txn:
    txn.set("key", "value")
    ...
    assert txn.get("key") == "value"

Get a value from a parent transaction:

with transaction() as parent:
    parent.set("key", "parent_value")
    with transaction() as child:
        assert child.get("key") == "parent_value"

Update a stored value:

with transaction() as txn:
    txn.set("key", [1, 2, 3])
    value = txn.get("key")
    value.append(4)
    # Stored value is not updated until `.set` is called
    assert value == [1, 2, 3, 4]
    assert txn.get("key") == [1, 2, 3]

    txn.set("key", value)
    assert txn.get("key") == [1, 2, 3, 4]
Source code in src/prefect/transactions.py
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
def get(self, name: str, default: Any = NotSet) -> Any:
    """
    Get a stored value from the transaction.

    Child transactions will return values from their parents unless a value with
    the same name is set in the child transaction.

    Direct changes to returned values will not update the stored value. To update the
    stored value, use the `set` method.

    Args:
        name: The name of the value to get
        default: The default value to return if the value is not found

    Returns:
        The value from the transaction

    Examples:
        Get a value from the transaction:
        ```python
        with transaction() as txn:
            txn.set("key", "value")
            ...
            assert txn.get("key") == "value"
        ```

        Get a value from a parent transaction:
        ```python
        with transaction() as parent:
            parent.set("key", "parent_value")
            with transaction() as child:
                assert child.get("key") == "parent_value"
        ```

        Update a stored value:
        ```python
        with transaction() as txn:
            txn.set("key", [1, 2, 3])
            value = txn.get("key")
            value.append(4)
            # Stored value is not updated until `.set` is called
            assert value == [1, 2, 3, 4]
            assert txn.get("key") == [1, 2, 3]

            txn.set("key", value)
            assert txn.get("key") == [1, 2, 3, 4]
        ```
    """
    # deepcopy to prevent mutation of stored values
    value = copy.deepcopy(self._stored_values.get(name, NotSet))
    if value is NotSet:
        # if there's a parent transaction, get the value from the parent
        parent = self.get_parent()
        if parent is not None:
            value = parent.get(name, default)
        # if there's no parent transaction, use the default
        elif default is not NotSet:
            value = default
        else:
            raise ValueError(f"Could not retrieve value for unknown key: {name}")
    return value

set(name, value)

Set a stored value in the transaction.

Parameters:

Name Type Description Default
name str

The name of the value to set

required
value Any

The value to set

required

Examples:

Set a value for use later in the transaction:

with transaction() as txn:
    txn.set("key", "value")
    ...
    assert txn.get("key") == "value"
Source code in src/prefect/transactions.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def set(self, name: str, value: Any) -> None:
    """
    Set a stored value in the transaction.

    Args:
        name: The name of the value to set
        value: The value to set

    Examples:
        Set a value for use later in the transaction:
        ```python
        with transaction() as txn:
            txn.set("key", "value")
            ...
            assert txn.get("key") == "value"
        ```
    """
    self._stored_values[name] = value

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

Stage a value to be committed later.

Source code in src/prefect/transactions.py
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
def stage(
    self,
    value: Any,
    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
 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
@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)
            active_workers = await client.read_workers_for_work_pool(
                work_pool_name,
                worker_filter=WorkerFilter(status=WorkerFilterStatus(any_=["ONLINE"])),
            )
    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/deploy/run-flows-in-local-processes"
            )
        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/deploy/run-flows-in-local-processes "
                " 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
            and not active_workers
        ):
            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:"
                f"\n\t[blue]$ prefect worker start --pool {work_pool_name!r}[/]",
            )
        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)

flow(__fn: Callable[P, R]) -> Flow[P, R]
flow(*, 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: 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) -> Callable[[Callable[P, R]], Flow[P, R]]

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
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
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
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)

get_client(httpx_settings: Optional[Dict[str, Any]] = None, sync_client: Literal[False] = False) -> PrefectClient
get_client(httpx_settings: Optional[Dict[str, Any]] = None, sync_client: Literal[True] = True) -> SyncPrefectClient

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
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
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

    # 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 sync_client:
        if client_ctx := prefect.context.SyncClientContext.get():
            if client_ctx.client and client_ctx._httpx_settings == httpx_settings:
                return client_ctx.client
    else:
        if client_ctx := prefect.context.AsyncClientContext.get():
            if (
                client_ctx.client
                and client_ctx._httpx_settings == httpx_settings
                and loop in (client_ctx.client._loop, None)
            ):
                return client_ctx.client

    api = PREFECT_API_URL.value()
    server_type = None

    if not api and PREFECT_SERVER_ALLOW_EPHEMERAL_MODE:
        # create an ephemeral API if none was provided
        from prefect.server.api.server import SubprocessASGIServer

        server = SubprocessASGIServer()
        server.start()
        assert server.server_process is not None, "Server process did not start"

        api = server.api_url
        server_type = ServerType.EPHEMERAL
    elif not api and not PREFECT_SERVER_ALLOW_EPHEMERAL_MODE:
        raise ValueError(
            "No Prefect API URL provided. Please set PREFECT_API_URL to the address of a running Prefect server."
        )

    if sync_client:
        return SyncPrefectClient(
            api,
            api_key=PREFECT_API_KEY.value(),
            httpx_settings=httpx_settings,
            server_type=server_type,
        )
    else:
        return PrefectClient(
            api,
            api_key=PREFECT_API_KEY.value(),
            httpx_settings=httpx_settings,
            server_type=server_type,
        )

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 Optional[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
 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
def get_run_logger(
    context: Optional["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

pause_flow_run(wait_for_input: None = None, timeout: int = 3600, poll_interval: int = 10, key: Optional[str] = None) -> None
pause_flow_run(wait_for_input: Type[T], timeout: int = 3600, poll_interval: int = 10, key: Optional[str] = None) -> 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.

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)

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
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
def serve(
    *args: "RunnerDeployment",
    pause_on_shutdown: bool = True,
    print_starting_message: bool = True,
    limit: Optional[int] = None,
    **kwargs,
):
    """
    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:
        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
        )

    try:
        loop = asyncio.get_running_loop()
    except RuntimeError as exc:
        if "no running event loop" in str(exc):
            loop = None
        else:
            raise

    try:
        if loop is not None:
            loop.run_until_complete(runner.start())
        else:
            asyncio.run(runner.start())
    except (KeyboardInterrupt, TerminationSignal) as exc:
        logger.info(f"Received {type(exc).__name__}, shutting down...")
        if loop is not None:
            loop.stop()

suspend_flow_run(wait_for_input=None, flow_run_id=None, timeout=3600, key=None, client=None) async

suspend_flow_run(wait_for_input: None = None, flow_run_id: Optional[UUID] = None, timeout: Optional[int] = 3600, key: Optional[str] = None, client: PrefectClient = None) -> None
suspend_flow_run(wait_for_input: Type[T], flow_run_id: Optional[UUID] = None, timeout: Optional[int] = 3600, key: Optional[str] = None, client: PrefectClient = None) -> 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.

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
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
@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)

task(__fn: Callable[P, R]) -> Task[P, R]
task(*, 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: Optional[Callable[[TaskRunContext, Dict[str, Any]], Optional[str]]] = None, cache_expiration: Optional[datetime.timedelta] = None, task_run_name: Optional[Union[Callable[[], str], Callable[[Dict[str, Any]], str], str]] = None, retries: int = 0, retry_delay_seconds: Union[float, int, List[float], Callable[[int], List[float]]] = 0, 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) -> Callable[[Callable[P, R]], Task[P, R]]

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 Union[Callable[[TaskRunContext, Dict[str, Any]], Optional[str]], None]

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], Callable[[Dict[str, Any]], 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
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
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
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
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: Union[
        Callable[["TaskRunContext", Dict[str, Any]], Optional[str]], None
    ] = None,
    cache_expiration: Optional[datetime.timedelta] = None,
    task_run_name: Optional[
        Union[Callable[[], str], Callable[[Dict[str, Any]], 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,
            ),
        )