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

Viktor Karsakov
  • 157
  • 3
  • 10

3 Answers3

15

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.

blhsing
  • 91,368
  • 6
  • 71
  • 106
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.

blue_note
  • 27,712
  • 9
  • 72
  • 90
  • 1
    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 Oct 25 '18 at 15:03
  • @chepner: yes, but exiting the context manager *affects* the object assigned to `f`. I didn't say it disappears – blue_note Oct 25 '18 at 15:04
-1

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

Pykler
  • 14,565
  • 9
  • 41
  • 50
  • 1
    `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. – chepner Oct 25 '18 at 15:02