Home > Net >  Python 3.10 : Optional[Type] or Type | None
Python 3.10 : Optional[Type] or Type | None

Time:10-05

Now that Python 3.10 has been released, is there any preference when indicating that a parameter or returned value might be optional, i.e., can be None. So what is preferred:

Option 1:

def f(parameter: Optional[int]) -> Optional[str]:

Option 2:

def f(parameter: int | None) -> str | None:

Also, is there any preference between Type | None and None | Type?

CodePudding user response:

enter image description here

CodePudding user response:

I would personally go with Option 2 moving forward.

Also, just wanted to add this for awareness, but Python 3.7 can made to support this syntax using a __future__ import as shown below. This type checks just the same; I actually got the tip from the latest release notes from Pycharm, which I'm currently using.

from __future__ import annotations


def f(parameter: int | None) -> str | None:
    pass

CodePudding user response:

Non-authoritative, but I would expect Optional when

  • there is a default value provided (probably None)
  • None would be unusual for the caller to pass

While I would expect some Union or | to be used when

  • there is not a default value and/or the default is not None
  • None is also a valid value

See related suggestions at How do I add default parameters to functions when using type hinting?

  • Related