Python 3 type hinting for None?

fj123x picture fj123x · Oct 5, 2013 · Viewed 29.1k times · Source
def foo(
        hello: str='world', bar: str=None,
        another_string_or_None: str|????=None):
    pass

I'm trying to set a type hint in Python in a function, you can add more than one type hint with something: str|bool='default value', but, what are the type hinting for None? :/

Answer

mbdevpl picture mbdevpl · Oct 3, 2016

From your example:

def foo(
        hello: str='world', bar: str=None,
        another_string_or_None: str|????=None):
    ...

I've noticed that your use case is "something or None".

Since version 3.5, Python supports type annotations via typing module. And in your case, the recommended way of annotating is by using typing.Optional[something] hint. This has exact meaning you're looking for.

Therefore the hint for another_string_or_None would be:

import typing

def foo(
        hello: str='world', bar: str=None,
        another_string_or_None: typing.Optional[str]=None):
    ...