How to specify "nullable" return type with type hints
<p>Suppose I have a function:</p>

<pre><code>def get_some_date(some_argument: int=None) -&gt; %datetime_or_None%:
    if some_argument is not None and some_argument == 1:
        return datetime.utcnow()
    else:
        return None
</code></pre>

<p>How do I specify the return type for something that can be <code>None</code>?</p>

<p>Since your return type can be <code>datetime</code> (as returned from <code>datetime.utcnow()</code>) or <code>None</code> you should use <code>Optional[datetime]</code>:</p>

<pre><code>from typing import Optional

def get_some_date(some_argument: int=None) -&gt; Optional[datetime]:
    # as defined
</code></pre>

<p>From the documentation, <a href="https://docs.python.org/3/library/typing.html#typing.Optional" rel="nofollow"><code>Optional</code></a> is shorthand for:</p>

<blockquote>
  <p><code>Optional[X]</code> is equivalent to <code>Union[X, None]</code>.</p>
</blockquote>

<p>where <code>Union[X, Y]</code> means a value of type <code>X</code> or <code>Y</code>.</p>

<hr>

<p>If you want to be explicit due to concerns that others might stumble on <code>Optional</code> and not realize it's meaning, you could always use <code>Union</code>:</p>

<pre><code>from typing import Union

def get_some_date(some_argument: int=None) -&gt; Union[datetime, None]:
</code></pre>

<p><sub>As pointed out in the comments by @Michael0x2a <code>Union[T, None]</code> is tranformed to <code>Union[T, type(None)]</code> so no need to use <code>type</code> here.</sub></p>

<p>Visually these might differ but programmatically in both cases the result is <em>exactly the same</em>; <code>Union[datetime.datetime, NoneType]</code> will be the type stored in <code>get_some_date.__annotations__</code>:</p>

<pre><code>{'return': typing.Union[datetime.datetime, NoneType], 'some_argument': int}
</code></pre>

python python-3.x python-3.5 type-hinting