1515import inspect
1616import logging
1717import threading
18+ from collections .abc import Callable ,Iterator ,Mapping ,MutableMapping ,Sequence
1819from contextlib import AbstractContextManager ,contextmanager
1920from dataclasses import dataclass
2021from datetime import datetime ,timedelta
2122from typing import (
2223TYPE_CHECKING ,
2324Any ,
24- Callable ,
25- Iterator ,
2625List ,
27- Mapping ,
28- MutableMapping ,
2926NoReturn ,
3027Optional ,
31- Sequence ,
3228Tuple ,
3329Type ,
3430Union ,
@@ -53,7 +49,7 @@ def defn(fn: CallableType) -> CallableType: ...
5349
5450@overload
5551def defn (
56- * ,name :Optional [ str ] = None ,no_thread_cancel_exception :bool = False
52+ * ,name :str | None = None ,no_thread_cancel_exception :bool = False
5753)-> Callable [[CallableType ],CallableType ]: ...
5854
5955
@@ -64,9 +60,9 @@ def defn(
6460
6561
6662def defn (
67- fn :Optional [ CallableType ] = None ,
63+ fn :CallableType | None = None ,# type: ignore[reportInvalidTypeVarUse]
6864* ,
69- name :Optional [ str ] = None ,
65+ name :str | None = None ,
7066no_thread_cancel_exception :bool = False ,
7167dynamic :bool = False ,
7268):
@@ -111,11 +107,11 @@ class Info:
111107attempt :int
112108current_attempt_scheduled_time :datetime
113109heartbeat_details :Sequence [Any ]
114- heartbeat_timeout :Optional [ timedelta ]
110+ heartbeat_timeout :timedelta | None
115111is_local :bool
116- schedule_to_close_timeout :Optional [ timedelta ]
112+ schedule_to_close_timeout :timedelta | None
117113scheduled_time :datetime
118- start_to_close_timeout :Optional [ timedelta ]
114+ start_to_close_timeout :timedelta | None
119115started_time :datetime
120116task_queue :str
121117task_token :bytes
@@ -124,7 +120,7 @@ class Info:
124120workflow_run_id :str
125121workflow_type :str
126122priority :temporalio .common .Priority
127- retry_policy :Optional [ temporalio .common .RetryPolicy ]
123+ retry_policy :temporalio .common .RetryPolicy | None
128124"""The retry policy of this activity.
129125
130126 Note that the server may have set a different policy than the one provided when scheduling the activity.
@@ -151,7 +147,7 @@ def _logger_details(self) -> Mapping[str, Any]:
151147
152148@dataclass
153149class _ActivityCancellationDetailsHolder :
154- details :Optional [ ActivityCancellationDetails ] = None
150+ details :ActivityCancellationDetails | None = None
155151
156152
157153@dataclass (frozen = True )
@@ -183,20 +179,20 @@ def _from_proto(
183179class _Context :
184180info :Callable [[],Info ]
185181# This is optional because during interceptor init it is not present
186- heartbeat :Optional [ Callable [...,None ]]
182+ heartbeat :Callable [...,None ]| None
187183cancelled_event :_CompositeEvent
188184worker_shutdown_event :_CompositeEvent
189- shield_thread_cancel_exception :Optional [ Callable [[],AbstractContextManager ]]
190- payload_converter_class_or_instance :Union [
191- Type [temporalio .converter .PayloadConverter ],
192- temporalio .converter .PayloadConverter ,
193- ]
194- runtime_metric_meter :Optional [ temporalio .common .MetricMeter ]
195- client :Optional [ Client ]
185+ shield_thread_cancel_exception :Callable [[],AbstractContextManager ]| None
186+ payload_converter_class_or_instance :(
187+ type [temporalio .converter .PayloadConverter ]
188+ | temporalio .converter .PayloadConverter
189+ )
190+ runtime_metric_meter :temporalio .common .MetricMeter | None
191+ client :Client | None
196192cancellation_details :_ActivityCancellationDetailsHolder
197- _logger_details :Optional [ Mapping [str ,Any ]] = None
198- _payload_converter :Optional [ temporalio .converter .PayloadConverter ] = None
199- _metric_meter :Optional [ temporalio .common .MetricMeter ] = None
193+ _logger_details :Mapping [str ,Any ]| None = None
194+ _payload_converter :temporalio .converter .PayloadConverter | None = None
195+ _metric_meter :temporalio .common .MetricMeter | None = None
200196
201197@staticmethod
202198def current ()-> _Context :
@@ -258,9 +254,9 @@ def metric_meter(self) -> temporalio.common.MetricMeter:
258254@dataclass
259255class _CompositeEvent :
260256# This should always be present, but is sometimes lazily set internally
261- thread_event :Optional [ threading .Event ]
257+ thread_event :threading .Event | None
262258# Async event only for async activities
263- async_event :Optional [ asyncio .Event ]
259+ async_event :asyncio .Event | None
264260
265261def set (self )-> None :
266262if not self .thread_event :
@@ -279,7 +275,7 @@ async def wait(self) -> None:
279275raise RuntimeError ("not in async activity" )
280276await self .async_event .wait ()
281277
282- def wait_sync (self ,timeout :Optional [ float ] = None )-> None :
278+ def wait_sync (self ,timeout :float | None = None )-> None :
283279if not self .thread_event :
284280raise RuntimeError ("Missing event" )
285281self .thread_event .wait (timeout )
@@ -330,7 +326,7 @@ def info() -> Info:
330326return _Context .current ().info ()
331327
332328
333- def cancellation_details ()-> Optional [ ActivityCancellationDetails ] :
329+ def cancellation_details ()-> ActivityCancellationDetails | None :
334330"""Cancellation details of the current activity, if any. Once set, cancellation details do not change."""
335331return _Context .current ().cancellation_details .details
336332
@@ -398,7 +394,7 @@ async def wait_for_cancelled() -> None:
398394await _Context .current ().cancelled_event .wait ()
399395
400396
401- def wait_for_cancelled_sync (timeout :Optional [ Union [ timedelta , float ]] = None )-> None :
397+ def wait_for_cancelled_sync (timeout :timedelta | float | None = None )-> None :
402398"""Synchronously block while waiting for a cancellation request on this
403399 activity.
404400
@@ -437,7 +433,7 @@ async def wait_for_worker_shutdown() -> None:
437433
438434
439435def wait_for_worker_shutdown_sync (
440- timeout :Optional [ Union [ timedelta , float ]] = None ,
436+ timeout :timedelta | float | None = None ,
441437)-> None :
442438"""Synchronously block while waiting for shutdown to be called on the
443439 worker.
@@ -511,9 +507,7 @@ class LoggerAdapter(logging.LoggerAdapter):
511507 use by others. Default is False.
512508 """
513509
514- def __init__ (
515- self ,logger :logging .Logger ,extra :Optional [Mapping [str ,Any ]]
516- )-> None :
510+ def __init__ (self ,logger :logging .Logger ,extra :Mapping [str ,Any ]| None )-> None :
517511"""Create the logger adapter."""
518512super ().__init__ (logger ,extra or {})
519513self .activity_info_on_message = True
@@ -522,7 +516,7 @@ def __init__(
522516
523517def process (
524518self ,msg :Any ,kwargs :MutableMapping [str ,Any ]
525- )-> Tuple [Any ,MutableMapping [str ,Any ]]:
519+ )-> tuple [Any ,MutableMapping [str ,Any ]]:
526520"""Override to add activity details."""
527521if (
528522self .activity_info_on_message
@@ -559,16 +553,16 @@ def base_logger(self) -> logging.Logger:
559553
560554@dataclass (frozen = True )
561555class _Definition :
562- name :Optional [ str ]
556+ name :str | None
563557fn :Callable
564558is_async :bool
565559no_thread_cancel_exception :bool
566560# Types loaded on post init if both are None
567- arg_types :Optional [ List [ Type ]] = None
568- ret_type :Optional [ Type ] = None
561+ arg_types :list [ type ] | None = None
562+ ret_type :type | None = None
569563
570564@staticmethod
571- def from_callable (fn :Callable )-> Optional [ _Definition ] :
565+ def from_callable (fn :Callable )-> _Definition | None :
572566defn = getattr (fn ,"__temporal_activity_definition" ,None )
573567if isinstance (defn ,_Definition ):
574568# We have to replace the function with the given callable here
@@ -592,7 +586,7 @@ def must_from_callable(fn: Callable) -> _Definition:
592586def _apply_to_callable (
593587fn :Callable ,
594588* ,
595- activity_name :Optional [ str ] ,
589+ activity_name :str | None ,
596590no_thread_cancel_exception :bool = False ,
597591 )-> None :
598592# Validate the activity