with statement

8. Compound statements - Python 3.10.0 documentation

다음 코드는 그 아래의 코드와 동일하다.

with EXPRESSION as TARGET:
    SUITE
manager = (EXPRESSION)
enter = type(manager).__enter__
exit = type(manager).__exit__
value = enter(manager)
hit_except = False

try:
    TARGET = value
    SUITE
except:
    hit_except = True
    if not exit(manager, *sys.exc_info()):
        raise
finally:
    if not hit_except:
        exit(manager, None, None, None)

하나 이상일 때 컨텍스트 매니저는 복수의 with 구문이 내포된 것처럼 실행된다.(3.1도입)

아래 두 코드가 동일한 효과

with A() as a, B() as b:
    SUITE
with A() as a:
    with B() as b:
        SUITE

다음은 여러 줄로 나누기 위해 3.10에서 도입됨.

with (
    A() as a,
    B() as b,
):
    SUITE