#100DaysOfCode in Python Transcripts
Chapter: Days 34-36: Refactoring / Pythonic code
Lecture: Refactoring 3: with statement (context managers)
0:00 Right, next up is the with statement.
0:02 You all have worked with files by now, I suppose.
0:05 The way to open and close files is like this.
0:12 That's fine, that's not optimal
0:14 but if an exception occurs between the open
0:17 and close statements.
0:18 Let's demo that here.
0:20 So we write hello and for some reason an exception happens.
0:25 The problem here is that the file
0:27 handle called f stayed open.
0:29 So if I check now for is f closed?
0:33 False, it's still open.
0:34 So it's leaking resources into your program
0:37 which is a problem, right?
0:38 One way to avoid this is to use try
0:40 and use except finally block.
0:41 Try an operation, you catch the exception, if there's one
0:44 and the finally block always execute,
0:47 so you could put f.close in
0:48 there to make sure it always closes, right?
0:51 You would write something like this.
0:56 Let's just trigger an exception.
0:58 I divide by zero which is going to
1:00 give me a ZeroDivision error.
1:03 Let's catch that here.
1:12 Finally, I will always close my file handle
1:17 and I do that here.
1:19 Open the file, write something,
1:21 trigger ZeroDivision error, catch it
1:23 and either working or failing, I always get f.close.
1:27 Let's see if the file handle now is closed.
1:31 And indeed it is closed.
1:32 That's cool, right?
1:33 This is much better code, but there's even
1:36 a better, more pathonic way to do the above
1:38 and it's to use a context manager or the with statement.
1:42 I can rewrite the previous code as with open
1:50 This is the same code and the nice thing
1:52 about with is once you go out of the block
1:54 it auto-closes your resource.
1:57 In this case the file handle f.
1:58 This raises the exception as we told it to do.
2:01 Let's see if f is closed.
2:06 And True.
2:07 Look at that.
2:08 I mean although I like try except finally,
2:10 it's definitely a good feature.
2:13 This is just shorter, more pathonic way to do it.
2:16 Use with statements or context manager if
2:19 you have to deal with resources that
2:21 have some sort of closure at the end.