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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With