Answer the question
In order to leave comments, you need to log in
Why is the with statement called?
Hello, Python has a with statement (context manager). Who knows why it's called that? With is "c, together with". Python is a beautiful language, most of the conditions are readable as text, but I can't understand with.
Answer the question
In order to leave comments, you need to log in
Quite a logical name. A statement with
declares some context that the code inside the statement block works with. The code can be translated almost verbatim:
with open('some.file') as f:
for line in f:
print(line)
с открыть('некоторый.файл') как f:
для каждой строки в f:
напечатать(строку)
The with statement is just syntactic sugar.
It is convenient to use it when writing classes for working with databases, files, as well as any network connections, where you constantly need to perform a number of routine operations.
"Under the hood" with performs two magic methods:
__enter__
when the context is opened, when the context
__exit__
is exited.
Accordingly, in order for your class to be used with the with construct, you just need to declare these two methods in your class and specify the operations that will be performed each time when "opening" and "closing".
Good article on this topic https://pavel-karateev.gitbook.io/intermediate-pyt...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question