Skip to content

Commit f22efea

Browse files
authored
Support PEP 604 union annotations (#256)
1 parent 677262a commit f22efea

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

temporalio/converter.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@
4949
if sys.version_info >= (3, 11):
5050
from enum import StrEnum
5151

52+
if sys.version_info >= (3, 10):
53+
from types import UnionType
54+
5255

5356
class PayloadConverter(ABC):
5457
"""Base payload converter to/from multiple payloads/values."""
@@ -1155,8 +1158,12 @@ def value_to_type(hint: Type, value: Any) -> Any:
11551158
raise TypeError(f"Value {value} not in literal values {type_args}")
11561159
return value
11571160

1161+
is_union = origin is Union
1162+
if sys.version_info >= (3, 10):
1163+
is_union = is_union or isinstance(origin, UnionType)
1164+
11581165
# Union
1159-
if origin is Union:
1166+
if is_union:
11601167
# Try each one. Note, Optional is just a union w/ none.
11611168
for arg in type_args:
11621169
try:

tests/test_converter.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,12 @@ def fail(hint: Type, value: Any) -> None:
305305
ok(Union[int, str], "foo")
306306
ok(Union[MyDataClass, NestedDataClass], MyDataClass("foo", 5, SerializableEnum.FOO))
307307
ok(Union[MyDataClass, NestedDataClass], NestedDataClass("foo"))
308+
if sys.version_info >= (3, 10):
309+
ok(int | None, None)
310+
ok(int | None, 5)
311+
fail(int | None, "1")
312+
ok(MyDataClass | NestedDataClass, MyDataClass("foo", 5, SerializableEnum.FOO))
313+
ok(MyDataClass | NestedDataClass, NestedDataClass("foo"))
308314

309315
# NewType
310316
ok(NewIntType, 5)

0 commit comments

Comments
 (0)