python - Variable scope after using a 'with' statement

Viewed 2545

I didn't find the answer for this question on stackoverflow, so I thought it might be helpful to ask it, and have it here -

I am declaring a new dictionary after I open a file, in the following way -

with open('some_file.txt','r') as f:
    dict = json.loads(f.read()) #converts text to a dictionary

my question is - will I be able to reach dict content's even after the 'with' scope ends.

Thanks

3 Answers

Yes, in Python the scope of a variable ends only when the code block it's defined in ends, and the with statement is not a code block per the documentation:

The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified as a command line argument to the interpreter) is a code block. A script command (a command specified on the interpreter command line with the ā€˜-c’ option) is a code block. The string argument passed to the built-in functions eval() and exec() is a code block.

In python scope is defined by functions. There is no indentation scope (similar to "bracket" scope in other languages). The with part affects just the f object.

Yes you will, you will not be able to access f, everything else is fair game.

Related