Understanding "with" and Python's context managers

Поделиться
HTML-код
  • Опубликовано: 31 июл 2024
  • Why do we use "with" when opening files? Because "with" invokes the context manager protocol, ensuring that the file is flushed and closed at the end of the block. In this video, I explain what that means, and then show you how the protocol works, and how we can add it to our own classes.
  • НаукаНаука

Комментарии • 12

  • @sankhasubhrachatterjee5069
    @sankhasubhrachatterjee5069 8 месяцев назад +1

    Excellent explanation Sir. Thanks for this knowledge.

  • @moose304
    @moose304 8 месяцев назад +1

    I've always used the "with" context manager, but mostly because it's "convention" (plus not having to remember to close my file!, or waiting on it to close) I had no idea all the other details. This is great! Thanks Reuven!

    • @ReuvenLerner
      @ReuvenLerner  8 месяцев назад +1

      My pleasure -- glad to know it helped!

  • @retrain35yo87
    @retrain35yo87 2 месяца назад +1

    good lesson

  • @mansouralshamri1387
    @mansouralshamri1387 2 месяца назад +1

    I don't understand the trapping exceptions in the __exit__ part. Why did you return True?

    • @ReuvenLerner
      @ReuvenLerner  2 месяца назад +1

      You return True from `__exit__` to ensure that the exception isn't re-raised.

  • @Doggy_Styles_Coding
    @Doggy_Styles_Coding 8 месяцев назад +5

    Why do programmers like dark mode? Because light attracts bugs

  • @waynewatson7970
    @waynewatson7970 6 месяцев назад +1

    I ran the 2 cells in jupyter lab, and it created and wrote the file so quick, I could see all the lines in the file, not sure how yours was delayed?? on windows, running python3.9
    Cell1
    # I want to write to a file
    # I can use the "open" to open a file for writing (with the 'w' option)
    # help(open)
    f = open('myfile.txt', 'w')
    f.write('abcde
    ')
    f.write('fghij
    ')
    f.write('klmnop
    ')
    Cell2
    # use the Unix "cat" command to view the file
    !cat myfile.txt
    Output right away
    abcde
    fghij
    klmnop
    thanks.
    Never mind, it seems to be matching what you had now, so much to learn, thanks for always sharing your knowledge.

    • @ReuvenLerner
      @ReuvenLerner  6 месяцев назад +1

      I'm glad it's working! Note that if/when data is stored to a file is very much dependent on lots of factors. Only by flushing the buffer (or closing the file, which does the same thing, or using "with", which flushes + closes) can you be sure that the file was written to. But if you don't, then it might work just fine... you just can't be sure. Thanks so much for writing and telling me it worked.