+ 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?
4 ответов
+ 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.
+ 8
well I tested it with a normal variable, like
with 10 as x:
print(x)
but it got me an error...
+ 3
A tricky thing to google :) without the phrase "with statement" in quotes >> https://www.google.ie/search?q=JUMP_LINK__&&__python__&&__JUMP_LINK+%22with+statement%22&rlz=1CASMAE_enIE683IE683&oq=python+%22with+statement
+ 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