8

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?

gmolau
  • 2,815
  • 1
  • 22
  • 45

1 Answers1

14

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Hm, treating a default None as equivalent to Optional seems sensible, but your second link states that `--strict-optional` will become the default in the 'near future'. That means one has to use Optional unless one wants to see the checks fail later. – gmolau Apr 09 '18 at 00:38
  • Or you could pass the negating flag `--no-strict-optional` -- however, I find that the benefits of not having implicit nullability are significant so I recommend just using `Optional` where appropriate instead of relying on it being "implied" in some circumstances. – mgilson Apr 09 '18 at 00:49
  • I'm all for an explicit solution, I just think `Optional` is a very unfortunate name as it is long and lends itself to confuse optional types and optional arguments. At least there is some discussion about changing this (https://github.com/python/typing/issues/429). Anyway, thanks for your help! – gmolau Apr 09 '18 at 00:54
  • This is an older answer and at the time it was a good answer but PEP has updated now says "A past version of this PEP allowed type checkers to assume an optional type when the default value is None. Type checkers should move towards requiring the optional type to be made explicit." – dan webb May 29 '20 at 13:03