title: how to tell a python type checker that an optional definitely exists?
body: <p>I'm used to typescript, in which one can use a <code>!</code> to tell the type-checker to assume a value won't be null. Is there something analogous when using type annotations in python?</p>
  <p>A (contrived) example:</p>
  <p>When executing the expression <code>m.maybe_num + 3</code> in the code below, the enclosing <code>if</code> guarantees that <code>maybe_num</code> won't be <code>None</code>.  But the type-checker doesn't know that, and returns an error.  (Verified in <a href="https://mypy-play.net/?mypy=latest&amp;python=3.10." rel="nofollow noreferrer">https://mypy-play.net/?mypy=latest&amp;python=3.10.</a>) How can I tell the type-checker that I know better?</p>
  <pre class="lang-py prettyprint-override"><code>from typing import Optional
  
  class MyClass:
  
      def __init__(self, maybe_num: Optional[int]):
          self.maybe_num = maybe_num
          
      def has_a_num(self) -&gt; bool:
          return self.maybe_num is not None
  
      def three_more(self) -&gt; Optional[int]:
          if self.has_a_num:
              # mypy error: Unsupported operand types for + (&quot;None&quot; and &quot;int&quot;)
              return self.maybe_num + 3
          else:
              return None
  </code></pre>