Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable defined with with-statement available outside of with-block?

Tags:

python

Consider the following example:

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

I have read the language docs (2.7) for with-statement as well as PEP-343, but as far as I can tell they don't say anything on this matter.

In CPython 2.6.5 f does seem to be defined outside of the with-block, but I'd rather not rely on an implementation detail that could change.

like image 586
Heikki Toivonen Avatar asked Jun 21 '11 21:06

Heikki Toivonen


People also ask

What is the name of a variable defined outside of a function?

In Python, a variable declared outside of the function or in global scope is known as a global variable. This means that a global variable can be accessed inside or outside of the function.

What is the with statement in Python called?

In Python, the with statement replaces a try-catch block with a concise shorthand. More importantly, it ensures closing resources right after processing them. A common example of using the with statement is reading or writing to a file. A function or class that supports the with statement is known as a context manager.

Can context managers be used outside the with statement?

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

Which variables Cannot be accessed outside the function?

Variables declared inside any function with var keyword are called local variables. Local variables cannot be accessed or modified outside the function declaration.


2 Answers

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

like image 195
fuzzyman Avatar answered Sep 28 '22 06:09

fuzzyman


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 is often useful. For example

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

the context manager may be of use more than once.

like image 24
SingleNegationElimination Avatar answered Sep 28 '22 06:09

SingleNegationElimination