-1

I'm confused how the closed method on a file object can be executed successfully even after the file has been closed, as documented one of the tutorials.

>>> with open('workfile') as f:
...     read_data = f.read()
>>> f.closed
True

I would expect the f.closed command to fail because the with statement should close the file and f should no longer be available. How is the program still able to recognize the f file object after the it is closed?

Also, shouldn't the name f exist only within the with block? How is the program able to recognize the object outside of the with block?

eastern_muffin
  • 181
  • 2
  • 7
  • 1
    actually that's a thing with `with`, they don't create a new naming scope – Tomerikoo Aug 17 '19 at 21:54
  • Python doesn't do block scoping. See https://stackoverflow.com/q/6167923/4518341 – wjandrea Aug 17 '19 at 22:02
  • 2
    Closing a file object referred to via the variable `f` does not (and fundamentally *cannot*) change the value of `f`; it still refers to exactly the same object. That object is simply now in a state where most operations would return a "file is closed" error. Accessing the attribute `closed` (note: it's NOT a method) works exactly the same before or after. – jasonharper Aug 17 '19 at 22:26
  • `with`, as many other things in python, follows a protocol. It's for managing context. Please read about context managers and experiment. Then things will be much clearer – Pynchia Aug 17 '19 at 22:43

1 Answers1

-1

How is the program still able to recognize the f file object after the it is closed?

It just works, but is that really so much of a problem? Variables are not meant to be reused, some might say. For those, it would be a useless feature. For others, it would be good, or just alright.

[...] shouldn't the name f exist only within the with block? [...]

Probably.

[...] How is the program able to recognize the object outside of the with block?

As a matter of fact, the object, in the source code, exists before (and out of) the nested block (just right before and out of it). So the language designers' choice, even maybe arguably, makes sense.

1737973
  • 159
  • 18
  • 42