title: Get types in Python expression using MyPy as library
body: <p>I have some Python source code, and want to find out the type of a variable. For example given the string</p>
  
  <pre><code>"""
  greeting = "Hello"
  """
  </code></pre>
  
  <p>I want to have <code>get_type('greeting') == str</code>. Or a more complex example:</p>
  
  <pre><code>"""
  def test(input: str):
      output = len(input)
      return str
  """
  </code></pre>
  
  <p>In pseudocode, I want to be able to do something like:</p>
  
  <pre><code>&gt;&gt;&gt; m = parse_module()
  &gt;&gt;&gt; m.functions['test'].locals['output'].get_type()
  int
  </code></pre>
  
  <p>It seems this should be possible with type annotations and MyPy in Python 3, but I can't figure out how. IDEs like VS code have become very good at guessing the types in python code, that is why I'm guessing there must be an exposed way to do this.</p>
  
  <p>There seems to be a module <a href="https://github.com/python/typed_ast" rel="nofollow noreferrer">typed-ast</a>, which is also used by MyPy, that gets me part of the way there. However, this does no type inference or propagation, it just gives me the explicit annotations as far as I understand. MyPy as an api, but it only lets you run the checker, and returns the same error messages as the command line tool. I am looking for a way to "reach into" MyPy, and get some of the inferred information out - or some alternative solution I haven't thought of.</p>