+ 10

How exactly does "with" work?

It is used in the course to assign a file to a temporary variable to ensure it gets closed. I tested around with it using other values, but it didn't quite work. Can anybody explain it?

25th Apr 2017, 6:11 PM
Supersebi3
Supersebi3 - avatar
4 odpowiedzi
+ 8
It kind of ensures that the variable or data resource you use it with, gets cleaned up after being used *even if* an exception is raised. For most of the cases it's just a double-check protection of data consistency.
25th Apr 2017, 6:49 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 8
well I tested it with a normal variable, like with 10 as x: print(x) but it got me an error...
25th Apr 2017, 7:16 PM
Supersebi3
Supersebi3 - avatar
26th Apr 2017, 1:01 AM
Lium Goon
Lium Goon - avatar
+ 1
Well, for that you need to learn about __dunder__ methods... It is a bit complicated. A context manager (basically the with statement) first runs the __enter__ method of the object (e.g. thing in the case of: with thing), then runs your code, and finally runs the __exit__ method. And that explanation is over-simplified... To learn how exactly it works, you have to explore the source of Python. Basically, a context managers does some setup, runs your code, and then tears up the setup things
25th Apr 2017, 8:53 PM
Amaras A
Amaras A - avatar