Search code examples
pythonpython-typingmypy

Should arguments that default to None always be type hinted as Optional[]?


Compare these two functions:

from typing import Optional

def foo1(bar: str = None) -> None:
    print(bar)

def foo2(bar: Optional[str] = None) -> None:
    print(bar)

Mypy doesn't complain about either of them. Is the Optional[] really necessary then? Is there any subtle difference between these two declarations?


Solution

  • PEP-484 has been updated since the original answer was written. In modern python-type-checking, it is preferred to make the Optional explicit. To quote the PEP:

    A past version of this PEP allowed type checkers to assume an optional type when the default value is None, as in this code:

    def handle_employee(e: Employee = None): ...

    This would have been treated as equivalent to:

    def handle_employee(e: Optional[Employee] = None) -> None: ...

    This is no longer the recommended behavior. Type checkers should move towards requiring the optional type to be made explicit.