ReplaceUnionWithOptionalRule
Enforces the use of Optional[T]
over Union[T, None]
and Union[None, T]
.
See https://docs.python.org/3/library/typing.html#typing.Optional to learn more about Optionals.
Message
Optional[T] is preferred over Union[T, None] or Union[None, T]. Learn more: https://docs.python.org/3/library/typing.html#typing.Optional
Has Autofix: Yes
VALID Code Examples
# 1:
def func() -> Optional[str]:
pass
# 2:
def func() -> Optional[Dict]:
pass
# 3:
def func() -> Union[str, int, None]:
pass
INVALID Code Examples
# 1:
def func() -> Union[str, None]:
pass
# 2:
from typing import Optional
def func() -> Union[Dict[str, int], None]:
pass
Autofix:
---
+++
@@ -1,4 +1,4 @@
from typing import Optional
-def func() -> Union[Dict[str, int], None]:
+def func() -> Optional[Dict[str, int]]:
pass
# 3:
from typing import Optional
def func() -> Union[str, None]:
pass
Autofix:
---
+++
@@ -1,4 +1,4 @@
from typing import Optional
-def func() -> Union[str, None]:
+def func() -> Optional[str]:
pass
# 4:
from typing import Optional
def func() -> Union[Dict, None]:
pass
Autofix:
---
+++
@@ -1,4 +1,4 @@
from typing import Optional
-def func() -> Union[Dict, None]:
+def func() -> Optional[Dict]:
pass