title: How does the 'with' statement work in Flask (Jinja2)?
body: <p>In Python you can use the <code>with</code> statement like this (<a href="http://effbot.org/zone/python-with-statement.htm" rel="noreferrer">source</a>):</p>
  
  <pre><code>class controlled_execution:
      def __enter__(self):
          # set things up
          return thing
      def __exit__(self, type, value, traceback):
          # tear things down
  
  with controlled_execution() as thing:
       # some code
  </code></pre>
  
  <p>In Flask/Jinja2, the standard procedure for using flash messages is the following (<a href="http://flask.pocoo.org/docs/0.10/patterns/flashing/" rel="noreferrer">source</a>):</p>
  
  <pre><code>{% with messages = get_flashed_messages() %}
    {% if messages %}
      {% for message in messages %}
        &lt;!-- do stuff with `message` --&gt;
      {% endfor %}        
    {% endif %}
  {% endwith %}
  </code></pre>
  
  <p>I'd like to know how <code>{% with messages = get_flashed_messages() %}</code> works in terms of syntax.</p>
  
  <p>I failed to recreate it in pure Python:</p>
  
  <ul>
  <li><code>with messages = get_flashed_messages(): pass</code> raises <code>SyntaxError</code></li>
  <li><code>with get_flashed_messages() as messages: pass</code> raises <code>AttributeError: __exit__</code></li>
  </ul>
  
  <p>(I've imported <code>get_flashed_messages</code> from <code>flask</code> in both cases).</p>