I'm trying to understand how to use the Optional type hint. From PEP-484, I know I can use Optional for def test(a: int = None) either as def test(a: Union[int, None]) or def test(a: Optional[int]).
But how about following examples?
def test(a : dict = None):
#print(a) ==> {'a': 1234}
#or
#print(a) ==> None
def test(a : list = None):
#print(a) ==> [1,2,3,4, 'a', 'b']
#or
#print(a) ==> None
If Optional[type] seems to mean the same thing as Union[type, None], why should I use Optional[] at all?
Directly from mypy typing module docs.
While the accepted answer is the correct answer, one additional thing to note is that, in the context of kwargs, both Optional[...] and Union[..., None] are redundant and unnecessary. If you're immediately setting your kwarg to None, then both mypy and IDEs assume the obvious and automatically treat the arg as Optional[...].
IDE:
mypy:
For variables and method/function return values, Optional[...] is still necessary, however, as mypy cannot know, in those cases, to automatically assume anything.