R
R
Roper2222020-05-02 14:17:55
Python
Roper222, 2020-05-02 14:17:55

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

2 answer(s)
S
Sergey Gornostaev, 2020-05-02
@Roper222

Quite a logical name. A statement withdeclares 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:
        напечатать(строку)

A
Andrey Sobolev, 2020-05-02
@Sobolev5

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 question

Ask a Question

731 491 924 answers to any question