Confused about Python's with statement

前端 未结 2 949
一整个雨季
一整个雨季 2021-02-10 03:41

I saw some code in the Whoosh documentation:

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


        
2条回答
  •  暖寄归人
    2021-02-10 04:19

    Example straight from 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)
    

提交回复
热议问题