#100DaysOfCode in Python Transcripts
Chapter: Days 34-36: Refactoring / Pythonic code
Lecture: Refactoring 3: with statement (context managers)

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Right, next up is the with statement. You all have worked with files by now, I suppose. The way to open and close files is like this.
0:13 That's fine, that's not optimal but if an exception occurs between the open and close statements. Let's demo that here.
0:21 So we write hello and for some reason an exception happens. The problem here is that the file handle called f stayed open.
0:30 So if I check now for is f closed? False, it's still open. So it's leaking resources into your program which is a problem, right?
0:39 One way to avoid this is to use try and use except finally block. Try an operation, you catch the exception, if there's one
0:45 and the finally block always execute, so you could put f.close in there to make sure it always closes, right? You would write something like this.
0:57 Let's just trigger an exception. I divide by zero which is going to give me a ZeroDivision error. Let's catch that here.
1:13 Finally, I will always close my file handle and I do that here. Open the file, write something, trigger ZeroDivision error, catch it
1:24 and either working or failing, I always get f.close. Let's see if the file handle now is closed. And indeed it is closed. That's cool, right?
1:34 This is much better code, but there's even a better, more pathonic way to do the above and it's to use a context manager or the with statement.
1:43 I can rewrite the previous code as with open This is the same code and the nice thing about with is once you go out of the block
1:55 it auto-closes your resource. In this case the file handle f. This raises the exception as we told it to do. Let's see if f is closed. And True.
2:08 Look at that. I mean although I like try except finally, it's definitely a good feature. This is just shorter, more pathonic way to do it.
2:17 Use with statements or context manager if you have to deal with resources that have some sort of closure at the end.


Talk Python's Mastodon Michael Kennedy's Mastodon