A variable defined using a statement operator, accessible outside the c-block?

Consider the following example:

with open('a.txt') as f: pass # Is f supposed to be defined here? 

I read the language documents (2.7) for for-statement as well as PEP-343, but as far as I can tell, they don't say anything about this.

In CPython 2.6.5, f seems to be defined outside the c-block, but I would rather not rely on implementation details that may change.

+48
python
Jun 21 2018-11-21T00:
source share
4 answers

Yes, the context manager will be available outside the with statement and is independent of implementation or version. with operators do not create a new execution area.

+91
Jun 21 '11 at 23:23
source share

with syntax:

 with foo as bar: baz() 

- approximately sugar for:

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

This is often useful: for example

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

context manager can be useful more than once.

+16
Jun 21 '11 at 21:50
source share

If f is a file, it will be closed outside the with statement.

For example, this

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

will print:

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

Details can be found in PEP-0343 under “Specification: Instruction“ c. ” Python scope rules (which can be annoying ) apply to f .

+10
Jun 21 2018-11-21T00:
source share

To answer Heikki's question in the comments: yes, this visible behavior is part of the python language specification and will work on any compatible Pythons (including PyPy, Jython and IronPython).

+8
Jun 21 2018-11-21T00:
source share



All Articles