[ACCEPTED]-Variable defined with with-statement available outside of with-block?-python

Accepted answer
Score: 174

Yes, the context manager will be available 3 outside the with statement and that is not 2 implementation or version dependent. with 1 statements do not create a new execution scope.

Score: 30

the with syntax:

with foo as bar:
    baz()

is approximately sugar for:

try:
    bar = foo.__enter__()
    baz()
finally:
    if foo.__exit__(*sys.exc_info()) and sys.exc_info():
        raise

This 2 is often useful. For example

import threading
with threading.Lock() as myLock:
    frob()

with myLock:
    frob_some_more()

the context 1 manager may be of use more than once.

Score: 17

In case f is a file, it will be appear closed 4 outside the with statement.

For example, this

f = 42
print f
with open('6432134.py') as f:
    print f
print f

would 3 print:

42
<open file '6432134.py', mode 'r' at 0x10050fb70>
<closed file '6432134.py', mode 'r' at 0x10050fb70>

You can find the details in PEP-0343 under 2 the section Specification: The 'with' Statement. Python scope rules (which might be irritating) apply to 1 f as well.

Score: 11

To answer Heikki's question in the comments: yes, this 4 scoping behavior is part of the python language 3 specification and will work on any and all 2 compliant Pythons (which includes PyPy, Jython, and 1 IronPython).

More Related questions