对Python的语句感到困惑

时间:2011-08-01 12:15:08

标签: python

我在Whoosh文档中看到了一些代码:

with ix.searcher() as searcher:
    query = QueryParser("content", ix.schema).parse(u"ship")
    results = searcher.search(query)

我读到with语句执行__ enter__和__ exit__方法,它们在“with file_pointer:”或“with lock:”形式中非常有用。但没有任何文献能够启发。当在“with”形式和传统形式之间进行翻译(是的,它是主观的)时,各种例子都显示出不一致。

请解释

  • 什么是声明
  • 和“as”声明
  • 以及在两种表单之间进行翻译的最佳做法
  • 什么类的课程借给他们

后记

关于http://effbot.org/zone/python-with-statement.htm的文章有最好的解释。当我滚动到页面底部并看到熟悉的文件操作时,一切都变得清晰了。 https://stackoverflow.com/users/190597/unutbu,希望你回答而不是评论。

2 个答案:

答案 0 :(得分:9)

直接来自PEP-0343的示例:

with EXPR as VAR:
   BLOCK

#translates to:

mgr = (EXPR)
exit = type(mgr).__exit__  # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
    try:
        VAR = value  # Only if "as VAR" is present
        BLOCK
    except:
        # The exceptional case is handled here
        exc = False
        if not exit(mgr, *sys.exc_info()):
            raise
        # The exception is swallowed if exit() returns true
finally:
    # The normal and non-local-goto cases are handled here
    if exc:
        exit(mgr, None, None, None)

答案 1 :(得分:2)

阅读http://www.python.org/dev/peps/pep-0343/它解释了with语句的含义以及它以try .. finally形式的外观。

相关问题