【发布时间】:2015-04-09 21:19:57
【问题描述】:
在 Python 中,您可以像这样使用 with 语句 (source):
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
在 Flask/Jinja2 中,使用 flash 消息的标准过程如下(source):
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<!-- do stuff with `message` -->
{% endfor %}
{% endif %}
{% endwith %}
我想知道{% with messages = get_flashed_messages() %} 在语法方面的工作原理。
我未能在纯 Python 中重新创建它:
-
with messages = get_flashed_messages(): pass提高SyntaxError -
with get_flashed_messages() as messages: pass提高AttributeError: __exit__
(在这两种情况下,我都从flask 导入了get_flashed_messages)。
【问题讨论】: