Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - Variable scope after using a 'with' statement [duplicate]

Tags:

python

scope

file

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

like image 439
Viktor Karsakov Avatar asked Oct 25 '18 14:10

Viktor Karsakov


1 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.

like image 89
blhsing Avatar answered Oct 21 '22 14:10

blhsing