0

I was reading a book on Python on my plane trip. I come from C++. The book was describing how to read files. I described the with keyword and said that the file would close when the block's scope was exited.

The book didn't go into details on how 'close()' actually got called. To me, this implies something akin to a destructor in the file object class. The with looks like a 'using' in C#. Am I correct? Did the book just skip over the details to keep it simple? Is there some manner of destructor or finalizer in python that I should be aware of and study up on?

Christopher Pisz
  • 3,757
  • 4
  • 29
  • 65
  • 1
    It's not a destructor or finalizer. It's highly analogous to C# `using`. – user2357112 Feb 26 '19 at 17:57
  • Related reading: https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers. TLDR: `__exit__` is kind of like a destructor for context managers. – Kevin Feb 26 '19 at 17:58
  • 1
    Python has finalizers, but that is **not** what `with` does. The `with` statement is sugar for some `try...finally` code, just like `using` in C#. – Dietrich Epp Feb 26 '19 at 17:58

0 Answers0