10

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

2
  • 6
    Why not try it out and see? Commented Oct 25, 2018 at 14:55
  • 1
    1) thought would be helpful to have it here for others 2) also looking for why it is the way it is (i.e. why is it different from the variable's scope inside the 'if' statements for example) Commented Oct 25, 2018 at 15:07

3 Answers 3

16

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

The with statement only assigns to f, introducing the name into the current containing scope if necessary. The name remains in scope after the with statement completes.
@chepner: yes, but exiting the context manager affects the object assigned to f. I didn't say it disappears
-1

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

1 Comment

f remains in scope. The underlying file is closed, but in general whatever object is bound by the as keyword in the with statement remains available after the with, until the end of the enclosing block.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.