Skip to content

Commit e977604

Browse files
committed
Add workflow.in_workflow() utility
Fixes temporalio#415
1 parent 49ca10e commit e977604

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

temporalio/workflow.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -830,6 +830,11 @@ def instance() -> Any:
830830
return _Runtime.current().workflow_instance()
831831

832832

833+
def in_workflow() -> bool:
834+
"""Whether the code is currently running in a workflow."""
835+
return _Runtime.maybe_current() is not None
836+
837+
833838
def memo() -> Mapping[str, Any]:
834839
"""Current workflow's memo values, converted without type hints.
835840

tests/worker/test_workflow.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6990,3 +6990,24 @@ async def test_update_handler_semaphore_acquisition_respects_timeout(
69906990
ever_in_critical_section=3, peak_in_critical_section=3
69916991
),
69926992
)
6993+
6994+
6995+
def check_in_workflow() -> str:
6996+
return "in workflow" if workflow.in_workflow() else "not in workflow"
6997+
6998+
6999+
@workflow.defn
7000+
class InWorkflowUtilWorkflow:
7001+
@workflow.run
7002+
async def run(self) -> str:
7003+
return check_in_workflow()
7004+
7005+
7006+
async def test_in_workflow_util(client: Client):
7007+
assert check_in_workflow() == "not in workflow"
7008+
async with new_worker(client, InWorkflowUtilWorkflow) as worker:
7009+
assert "in workflow" == await client.execute_workflow(
7010+
InWorkflowUtilWorkflow.run,
7011+
id=f"workflow-{uuid.uuid4()}",
7012+
task_queue=worker.task_queue,
7013+
)

0 commit comments

Comments
 (0)