.. _ReplaceUnionWithOptionalRule:

============================
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:







.. code-block:: python


    def func() -> Optional[str]:
        pass





# 2:







.. code-block:: python


    def func() -> Optional[Dict]:
        pass





# 3:







.. code-block:: python


    def func() -> Union[str, int, None]:
        pass





---------------------
INVALID Code Examples
---------------------

# 1:







.. code-block:: python


    def func() -> Union[str, None]:
        pass





# 2:







.. code-block:: python


    from typing import Optional
    def func() -> Union[Dict[str, int], None]:
        pass





Autofix:

.. code-block:: python

    --- 
    +++ 
    @@ -1,4 +1,4 @@
 
     from typing import Optional
    -def func() -> Union[Dict[str, int], None]:
    +def func() -> Optional[Dict[str, int]]:
         pass

# 3:







.. code-block:: python


    from typing import Optional
    def func() -> Union[str, None]:
        pass





Autofix:

.. code-block:: python

    --- 
    +++ 
    @@ -1,4 +1,4 @@
 
     from typing import Optional
    -def func() -> Union[str, None]:
    +def func() -> Optional[str]:
         pass

.. container:: toggle


    # 4:







    .. code-block:: python


        from typing import Optional
        def func() -> Union[Dict, None]:
            pass





    Autofix:

    .. code-block:: python

        --- 
        +++ 
        @@ -1,4 +1,4 @@
 
         from typing import Optional
        -def func() -> Union[Dict, None]:
        +def func() -> Optional[Dict]:
             pass

