prefect-client 3.1.8__py3-none-any.whl → 3.1.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
prefect/flows.py CHANGED
@@ -364,7 +364,7 @@ class Flow(Generic[P, R]):
364
364
  self._entrypoint: Optional[str] = None
365
365
 
366
366
  module = fn.__module__
367
- if module in ("__main__", "__prefect_loader__"):
367
+ if module and (module == "__main__" or module.startswith("__prefect_loader_")):
368
368
  module_name = inspect.getfile(fn)
369
369
  module = module_name if module_name != "__main__" else module
370
370
 
@@ -924,10 +924,10 @@ class Flow(Generic[P, R]):
924
924
  @classmethod
925
925
  @sync_compatible
926
926
  async def from_source(
927
- cls: Type["Flow[P, R]"],
927
+ cls,
928
928
  source: Union[str, "RunnerStorage", ReadableDeploymentStorage],
929
929
  entrypoint: str,
930
- ) -> "Flow[P, R]":
930
+ ) -> "Flow[..., Any]":
931
931
  """
932
932
  Loads a flow from a remote source.
933
933
 
@@ -1025,7 +1025,7 @@ class Flow(Generic[P, R]):
1025
1025
 
1026
1026
  full_entrypoint = str(storage.destination / entrypoint)
1027
1027
  flow = cast(
1028
- Flow[P, R],
1028
+ "Flow[..., Any]",
1029
1029
  await from_async.wait_for_call_in_new_thread(
1030
1030
  create_call(load_flow_from_entrypoint, full_entrypoint)
1031
1031
  ),
@@ -1408,194 +1408,200 @@ class Flow(Generic[P, R]):
1408
1408
  raise new_exception
1409
1409
 
1410
1410
 
1411
- @overload
1412
- def flow(__fn: Callable[P, R]) -> Flow[P, R]:
1413
- ...
1414
-
1415
-
1416
- @overload
1417
- def flow(
1418
- *,
1419
- name: Optional[str] = None,
1420
- version: Optional[str] = None,
1421
- flow_run_name: Optional[Union[Callable[[], str], str]] = None,
1422
- retries: Optional[int] = None,
1423
- retry_delay_seconds: Optional[Union[int, float]] = None,
1424
- task_runner: Optional[TaskRunner[PrefectFuture[R]]] = None,
1425
- description: Optional[str] = None,
1426
- timeout_seconds: Union[int, float, None] = None,
1427
- validate_parameters: bool = True,
1428
- persist_result: Optional[bool] = None,
1429
- result_storage: Optional[ResultStorage] = None,
1430
- result_serializer: Optional[ResultSerializer] = None,
1431
- cache_result_in_memory: bool = True,
1432
- log_prints: Optional[bool] = None,
1433
- on_completion: Optional[list[StateHookCallable]] = None,
1434
- on_failure: Optional[list[StateHookCallable]] = None,
1435
- on_cancellation: Optional[list[StateHookCallable]] = None,
1436
- on_crashed: Optional[list[StateHookCallable]] = None,
1437
- on_running: Optional[list[StateHookCallable]] = None,
1438
- ) -> Callable[[Callable[P, R]], Flow[P, R]]:
1439
- ...
1440
-
1441
-
1442
- def flow(
1443
- __fn: Optional[Callable[P, R]] = None,
1444
- *,
1445
- name: Optional[str] = None,
1446
- version: Optional[str] = None,
1447
- flow_run_name: Optional[Union[Callable[[], str], str]] = None,
1448
- retries: Optional[int] = None,
1449
- retry_delay_seconds: Union[int, float, None] = None,
1450
- task_runner: Optional[TaskRunner[PrefectFuture[R]]] = None,
1451
- description: Optional[str] = None,
1452
- timeout_seconds: Union[int, float, None] = None,
1453
- validate_parameters: bool = True,
1454
- persist_result: Optional[bool] = None,
1455
- result_storage: Optional[ResultStorage] = None,
1456
- result_serializer: Optional[ResultSerializer] = None,
1457
- cache_result_in_memory: bool = True,
1458
- log_prints: Optional[bool] = None,
1459
- on_completion: Optional[list[StateHookCallable]] = None,
1460
- on_failure: Optional[list[StateHookCallable]] = None,
1461
- on_cancellation: Optional[list[StateHookCallable]] = None,
1462
- on_crashed: Optional[list[StateHookCallable]] = None,
1463
- on_running: Optional[list[StateHookCallable]] = None,
1464
- ):
1465
- """
1466
- Decorator to designate a function as a Prefect workflow.
1411
+ class FlowDecorator:
1412
+ @overload
1413
+ def __call__(self, __fn: Callable[P, R]) -> Flow[P, R]:
1414
+ ...
1467
1415
 
1468
- This decorator may be used for asynchronous or synchronous functions.
1416
+ @overload
1417
+ def __call__(
1418
+ self,
1419
+ __fn: None = None,
1420
+ *,
1421
+ name: Optional[str] = None,
1422
+ version: Optional[str] = None,
1423
+ flow_run_name: Optional[Union[Callable[[], str], str]] = None,
1424
+ retries: Optional[int] = None,
1425
+ retry_delay_seconds: Optional[Union[int, float]] = None,
1426
+ task_runner: None = None,
1427
+ description: Optional[str] = None,
1428
+ timeout_seconds: Union[int, float, None] = None,
1429
+ validate_parameters: bool = True,
1430
+ persist_result: Optional[bool] = None,
1431
+ result_storage: Optional[ResultStorage] = None,
1432
+ result_serializer: Optional[ResultSerializer] = None,
1433
+ cache_result_in_memory: bool = True,
1434
+ log_prints: Optional[bool] = None,
1435
+ on_completion: Optional[list[StateHookCallable]] = None,
1436
+ on_failure: Optional[list[StateHookCallable]] = None,
1437
+ on_cancellation: Optional[list[StateHookCallable]] = None,
1438
+ on_crashed: Optional[list[StateHookCallable]] = None,
1439
+ on_running: Optional[list[StateHookCallable]] = None,
1440
+ ) -> Callable[[Callable[P, R]], Flow[P, R]]:
1441
+ ...
1469
1442
 
1470
- Flow parameters must be serializable by Pydantic.
1443
+ @overload
1444
+ def __call__(
1445
+ self,
1446
+ __fn: None = None,
1447
+ *,
1448
+ name: Optional[str] = None,
1449
+ version: Optional[str] = None,
1450
+ flow_run_name: Optional[Union[Callable[[], str], str]] = None,
1451
+ retries: Optional[int] = None,
1452
+ retry_delay_seconds: Optional[Union[int, float]] = None,
1453
+ task_runner: Optional[TaskRunner[PrefectFuture[R]]] = None,
1454
+ description: Optional[str] = None,
1455
+ timeout_seconds: Union[int, float, None] = None,
1456
+ validate_parameters: bool = True,
1457
+ persist_result: Optional[bool] = None,
1458
+ result_storage: Optional[ResultStorage] = None,
1459
+ result_serializer: Optional[ResultSerializer] = None,
1460
+ cache_result_in_memory: bool = True,
1461
+ log_prints: Optional[bool] = None,
1462
+ on_completion: Optional[list[StateHookCallable]] = None,
1463
+ on_failure: Optional[list[StateHookCallable]] = None,
1464
+ on_cancellation: Optional[list[StateHookCallable]] = None,
1465
+ on_crashed: Optional[list[StateHookCallable]] = None,
1466
+ on_running: Optional[list[StateHookCallable]] = None,
1467
+ ) -> Callable[[Callable[P, R]], Flow[P, R]]:
1468
+ ...
1471
1469
 
1472
- Args:
1473
- name: An optional name for the flow; if not provided, the name will be inferred
1474
- from the given function.
1475
- version: An optional version string for the flow; if not provided, we will
1476
- attempt to create a version string as a hash of the file containing the
1477
- wrapped function; if the file cannot be located, the version will be null.
1478
- flow_run_name: An optional name to distinguish runs of this flow; this name can
1479
- be provided as a string template with the flow's parameters as variables,
1480
- or a function that returns a string.
1481
- retries: An optional number of times to retry on flow run failure.
1482
- retry_delay_seconds: An optional number of seconds to wait before retrying the
1483
- flow after failure. This is only applicable if `retries` is nonzero.
1484
- task_runner: An optional task runner to use for task execution within the flow; if
1485
- not provided, a `ConcurrentTaskRunner` will be instantiated.
1486
- description: An optional string description for the flow; if not provided, the
1487
- description will be pulled from the docstring for the decorated function.
1488
- timeout_seconds: An optional number of seconds indicating a maximum runtime for
1489
- the flow. If the flow exceeds this runtime, it will be marked as failed.
1490
- Flow execution may continue until the next task is called.
1491
- validate_parameters: By default, parameters passed to flows are validated by
1492
- Pydantic. This will check that input values conform to the annotated types
1493
- on the function. Where possible, values will be coerced into the correct
1494
- type; for example, if a parameter is defined as `x: int` and "5" is passed,
1495
- it will be resolved to `5`. If set to `False`, no validation will be
1496
- performed on flow parameters.
1497
- persist_result: An optional toggle indicating whether the result of this flow
1498
- should be persisted to result storage. Defaults to `None`, which indicates
1499
- that Prefect should choose whether the result should be persisted depending on
1500
- the features being used.
1501
- result_storage: An optional block to use to persist the result of this flow.
1502
- This value will be used as the default for any tasks in this flow.
1503
- If not provided, the local file system will be used unless called as
1504
- a subflow, at which point the default will be loaded from the parent flow.
1505
- result_serializer: An optional serializer to use to serialize the result of this
1506
- flow for persistence. This value will be used as the default for any tasks
1507
- in this flow. If not provided, the value of `PREFECT_RESULTS_DEFAULT_SERIALIZER`
1508
- will be used unless called as a subflow, at which point the default will be
1509
- loaded from the parent flow.
1510
- cache_result_in_memory: An optional toggle indicating whether the cached result of
1511
- a running the flow should be stored in memory. Defaults to `True`.
1512
- log_prints: If set, `print` statements in the flow will be redirected to the
1513
- Prefect logger for the flow run. Defaults to `None`, which indicates that
1514
- the value from the parent flow should be used. If this is a parent flow,
1515
- the default is pulled from the `PREFECT_LOGGING_LOG_PRINTS` setting.
1516
- on_completion: An optional list of functions to call when the flow run is
1517
- completed. Each function should accept three arguments: the flow, the flow
1518
- run, and the final state of the flow run.
1519
- on_failure: An optional list of functions to call when the flow run fails. Each
1520
- function should accept three arguments: the flow, the flow run, and the
1521
- final state of the flow run.
1522
- on_cancellation: An optional list of functions to call when the flow run is
1523
- cancelled. These functions will be passed the flow, flow run, and final state.
1524
- on_crashed: An optional list of functions to call when the flow run crashes. Each
1525
- function should accept three arguments: the flow, the flow run, and the
1526
- final state of the flow run.
1527
- on_running: An optional list of functions to call when the flow run is started. Each
1528
- function should accept three arguments: the flow, the flow run, and the current state
1470
+ def __call__(
1471
+ self,
1472
+ __fn: Optional[Callable[P, R]] = None,
1473
+ *,
1474
+ name: Optional[str] = None,
1475
+ version: Optional[str] = None,
1476
+ flow_run_name: Optional[Union[Callable[[], str], str]] = None,
1477
+ retries: Optional[int] = None,
1478
+ retry_delay_seconds: Union[int, float, None] = None,
1479
+ task_runner: Optional[TaskRunner[PrefectFuture[R]]] = None,
1480
+ description: Optional[str] = None,
1481
+ timeout_seconds: Union[int, float, None] = None,
1482
+ validate_parameters: bool = True,
1483
+ persist_result: Optional[bool] = None,
1484
+ result_storage: Optional[ResultStorage] = None,
1485
+ result_serializer: Optional[ResultSerializer] = None,
1486
+ cache_result_in_memory: bool = True,
1487
+ log_prints: Optional[bool] = None,
1488
+ on_completion: Optional[list[StateHookCallable]] = None,
1489
+ on_failure: Optional[list[StateHookCallable]] = None,
1490
+ on_cancellation: Optional[list[StateHookCallable]] = None,
1491
+ on_crashed: Optional[list[StateHookCallable]] = None,
1492
+ on_running: Optional[list[StateHookCallable]] = None,
1493
+ ) -> Union[Flow[P, R], Callable[[Callable[P, R]], Flow[P, R]]]:
1494
+ """
1495
+ Decorator to designate a function as a Prefect workflow.
1529
1496
 
1530
- Returns:
1531
- A callable `Flow` object which, when called, will run the flow and return its
1532
- final state.
1497
+ This decorator may be used for asynchronous or synchronous functions.
1533
1498
 
1534
- Examples:
1535
- Define a simple flow
1499
+ Flow parameters must be serializable by Pydantic.
1536
1500
 
1537
- >>> from prefect import flow
1538
- >>> @flow
1539
- >>> def add(x, y):
1540
- >>> return x + y
1501
+ Args:
1502
+ name: An optional name for the flow; if not provided, the name will be inferred
1503
+ from the given function.
1504
+ version: An optional version string for the flow; if not provided, we will
1505
+ attempt to create a version string as a hash of the file containing the
1506
+ wrapped function; if the file cannot be located, the version will be null.
1507
+ flow_run_name: An optional name to distinguish runs of this flow; this name can
1508
+ be provided as a string template with the flow's parameters as variables,
1509
+ or a function that returns a string.
1510
+ retries: An optional number of times to retry on flow run failure.
1511
+ retry_delay_seconds: An optional number of seconds to wait before retrying the
1512
+ flow after failure. This is only applicable if `retries` is nonzero.
1513
+ task_runner: An optional task runner to use for task execution within the flow; if
1514
+ not provided, a `ConcurrentTaskRunner` will be instantiated.
1515
+ description: An optional string description for the flow; if not provided, the
1516
+ description will be pulled from the docstring for the decorated function.
1517
+ timeout_seconds: An optional number of seconds indicating a maximum runtime for
1518
+ the flow. If the flow exceeds this runtime, it will be marked as failed.
1519
+ Flow execution may continue until the next task is called.
1520
+ validate_parameters: By default, parameters passed to flows are validated by
1521
+ Pydantic. This will check that input values conform to the annotated types
1522
+ on the function. Where possible, values will be coerced into the correct
1523
+ type; for example, if a parameter is defined as `x: int` and "5" is passed,
1524
+ it will be resolved to `5`. If set to `False`, no validation will be
1525
+ performed on flow parameters.
1526
+ persist_result: An optional toggle indicating whether the result of this flow
1527
+ should be persisted to result storage. Defaults to `None`, which indicates
1528
+ that Prefect should choose whether the result should be persisted depending on
1529
+ the features being used.
1530
+ result_storage: An optional block to use to persist the result of this flow.
1531
+ This value will be used as the default for any tasks in this flow.
1532
+ If not provided, the local file system will be used unless called as
1533
+ a subflow, at which point the default will be loaded from the parent flow.
1534
+ result_serializer: An optional serializer to use to serialize the result of this
1535
+ flow for persistence. This value will be used as the default for any tasks
1536
+ in this flow. If not provided, the value of `PREFECT_RESULTS_DEFAULT_SERIALIZER`
1537
+ will be used unless called as a subflow, at which point the default will be
1538
+ loaded from the parent flow.
1539
+ cache_result_in_memory: An optional toggle indicating whether the cached result of
1540
+ a running the flow should be stored in memory. Defaults to `True`.
1541
+ log_prints: If set, `print` statements in the flow will be redirected to the
1542
+ Prefect logger for the flow run. Defaults to `None`, which indicates that
1543
+ the value from the parent flow should be used. If this is a parent flow,
1544
+ the default is pulled from the `PREFECT_LOGGING_LOG_PRINTS` setting.
1545
+ on_completion: An optional list of functions to call when the flow run is
1546
+ completed. Each function should accept three arguments: the flow, the flow
1547
+ run, and the final state of the flow run.
1548
+ on_failure: An optional list of functions to call when the flow run fails. Each
1549
+ function should accept three arguments: the flow, the flow run, and the
1550
+ final state of the flow run.
1551
+ on_cancellation: An optional list of functions to call when the flow run is
1552
+ cancelled. These functions will be passed the flow, flow run, and final state.
1553
+ on_crashed: An optional list of functions to call when the flow run crashes. Each
1554
+ function should accept three arguments: the flow, the flow run, and the
1555
+ final state of the flow run.
1556
+ on_running: An optional list of functions to call when the flow run is started. Each
1557
+ function should accept three arguments: the flow, the flow run, and the current state
1541
1558
 
1542
- Define an async flow
1559
+ Returns:
1560
+ A callable `Flow` object which, when called, will run the flow and return its
1561
+ final state.
1543
1562
 
1544
- >>> @flow
1545
- >>> async def add(x, y):
1546
- >>> return x + y
1563
+ Examples:
1564
+ Define a simple flow
1547
1565
 
1548
- Define a flow with a version and description
1566
+ >>> from prefect import flow
1567
+ >>> @flow
1568
+ >>> def add(x, y):
1569
+ >>> return x + y
1549
1570
 
1550
- >>> @flow(version="first-flow", description="This flow is empty!")
1551
- >>> def my_flow():
1552
- >>> pass
1571
+ Define an async flow
1553
1572
 
1554
- Define a flow with a custom name
1573
+ >>> @flow
1574
+ >>> async def add(x, y):
1575
+ >>> return x + y
1555
1576
 
1556
- >>> @flow(name="The Ultimate Flow")
1557
- >>> def my_flow():
1558
- >>> pass
1577
+ Define a flow with a version and description
1559
1578
 
1560
- Define a flow that submits its tasks to dask
1579
+ >>> @flow(version="first-flow", description="This flow is empty!")
1580
+ >>> def my_flow():
1581
+ >>> pass
1561
1582
 
1562
- >>> from prefect_dask.task_runners import DaskTaskRunner
1563
- >>>
1564
- >>> @flow(task_runner=DaskTaskRunner)
1565
- >>> def my_flow():
1566
- >>> pass
1567
- """
1568
- if __fn:
1569
- if isinstance(__fn, (classmethod, staticmethod)):
1570
- method_decorator = type(__fn).__name__
1571
- raise TypeError(f"@{method_decorator} should be applied on top of @flow")
1572
- return Flow(
1573
- fn=__fn,
1574
- name=name,
1575
- version=version,
1576
- flow_run_name=flow_run_name,
1577
- task_runner=task_runner,
1578
- description=description,
1579
- timeout_seconds=timeout_seconds,
1580
- validate_parameters=validate_parameters,
1581
- retries=retries,
1582
- retry_delay_seconds=retry_delay_seconds,
1583
- persist_result=persist_result,
1584
- result_storage=result_storage,
1585
- result_serializer=result_serializer,
1586
- cache_result_in_memory=cache_result_in_memory,
1587
- log_prints=log_prints,
1588
- on_completion=on_completion,
1589
- on_failure=on_failure,
1590
- on_cancellation=on_cancellation,
1591
- on_crashed=on_crashed,
1592
- on_running=on_running,
1593
- )
1594
- else:
1595
- return cast(
1596
- Callable[[Callable[P, R]], Flow[P, R]],
1597
- partial(
1598
- flow,
1583
+ Define a flow with a custom name
1584
+
1585
+ >>> @flow(name="The Ultimate Flow")
1586
+ >>> def my_flow():
1587
+ >>> pass
1588
+
1589
+ Define a flow that submits its tasks to dask
1590
+
1591
+ >>> from prefect_dask.task_runners import DaskTaskRunner
1592
+ >>>
1593
+ >>> @flow(task_runner=DaskTaskRunner)
1594
+ >>> def my_flow():
1595
+ >>> pass
1596
+ """
1597
+ if __fn:
1598
+ if isinstance(__fn, (classmethod, staticmethod)):
1599
+ method_decorator = type(__fn).__name__
1600
+ raise TypeError(
1601
+ f"@{method_decorator} should be applied on top of @flow"
1602
+ )
1603
+ return Flow(
1604
+ fn=__fn,
1599
1605
  name=name,
1600
1606
  version=version,
1601
1607
  flow_run_name=flow_run_name,
@@ -1615,8 +1621,49 @@ def flow(
1615
1621
  on_cancellation=on_cancellation,
1616
1622
  on_crashed=on_crashed,
1617
1623
  on_running=on_running,
1618
- ),
1619
- )
1624
+ )
1625
+ else:
1626
+ return cast(
1627
+ Callable[[Callable[P, R]], Flow[P, R]],
1628
+ partial(
1629
+ flow,
1630
+ name=name,
1631
+ version=version,
1632
+ flow_run_name=flow_run_name,
1633
+ task_runner=task_runner,
1634
+ description=description,
1635
+ timeout_seconds=timeout_seconds,
1636
+ validate_parameters=validate_parameters,
1637
+ retries=retries,
1638
+ retry_delay_seconds=retry_delay_seconds,
1639
+ persist_result=persist_result,
1640
+ result_storage=result_storage,
1641
+ result_serializer=result_serializer,
1642
+ cache_result_in_memory=cache_result_in_memory,
1643
+ log_prints=log_prints,
1644
+ on_completion=on_completion,
1645
+ on_failure=on_failure,
1646
+ on_cancellation=on_cancellation,
1647
+ on_crashed=on_crashed,
1648
+ on_running=on_running,
1649
+ ),
1650
+ )
1651
+
1652
+ if not TYPE_CHECKING:
1653
+ # Add from_source so it is available on the flow function we all know and love
1654
+ from_source = staticmethod(Flow.from_source)
1655
+ else:
1656
+ # Mypy loses the plot somewhere along the line, so the annotation is reconstructed
1657
+ # manually here.
1658
+ @staticmethod
1659
+ def from_source(
1660
+ source: Union[str, "RunnerStorage", ReadableDeploymentStorage],
1661
+ entrypoint: str,
1662
+ ) -> Union["Flow[..., Any]", Coroutine[Any, Any, "Flow[..., Any]"]]:
1663
+ ...
1664
+
1665
+
1666
+ flow = FlowDecorator()
1620
1667
 
1621
1668
 
1622
1669
  def _raise_on_name_with_banned_characters(name: Optional[str]) -> Optional[str]:
@@ -1636,10 +1683,6 @@ def _raise_on_name_with_banned_characters(name: Optional[str]) -> Optional[str]:
1636
1683
  return name
1637
1684
 
1638
1685
 
1639
- # Add from_source so it is available on the flow function we all know and love
1640
- flow.from_source = Flow.from_source
1641
-
1642
-
1643
1686
  def select_flow(
1644
1687
  flows: Iterable[Flow[P, R]],
1645
1688
  flow_name: Optional[str] = None,
@@ -1703,7 +1746,7 @@ def load_flow_from_entrypoint(
1703
1746
  The flow object from the script
1704
1747
 
1705
1748
  Raises:
1706
- FlowScriptError: If an exception is encountered while running the script
1749
+ ScriptError: If an exception is encountered while running the script
1707
1750
  MissingFlowError: If the flow function specified in the entrypoint does not exist
1708
1751
  """
1709
1752
 
@@ -1,6 +1,8 @@
1
1
  """
2
2
  2024-06-27: This surfaces an actionable error message for moved or removed objects in Prefect 3.0 upgrade.
3
3
  """
4
+ from typing import Any, Callable
5
+
4
6
  from prefect._internal.compatibility.migration import getattr_migration
5
7
 
6
- __getattr__ = getattr_migration(__name__)
8
+ __getattr__: Callable[[str], Any] = getattr_migration(__name__)
@@ -1,6 +1,8 @@
1
1
  """
2
2
  2024-06-27: This surfaces an actionable error message for moved or removed objects in Prefect 3.0 upgrade.
3
3
  """
4
+ from typing import Any, Callable
5
+
4
6
  from prefect._internal.compatibility.migration import getattr_migration
5
7
 
6
- __getattr__ = getattr_migration(__name__)
8
+ __getattr__: Callable[[str], Any] = getattr_migration(__name__)