What is the purpose of context manager in python

I read http://eigenhombre.com/2013/04/20/introduction-to-context-managers/ .

In him:

Context managers are a way of allocating and releasing a resource exactly where you need it. The simplest example is file access:

with file("/tmp/foo", "w") as foo:
    print >> foo, "Hello!"

This is essentially equivalent to:

foo = file("/tmp/foo", "w")
try:
    print >> foo, "Hello!"
finally:
    foo.close()

The article provides further clarifications, but I'm still not sure that I understand their purpose in a simple way. Can someone clarify. And what is context?

I looked at Attempting to understand python using operators and context managers , but again I'm not sure what the purpose of the context manager is? Is this just an alternative syntax for "try .. finally .." or is it their other purpose.

+4
1

- . ( ).

, :

f = open(path, "w")

. . , :

f.close()

:

f = open(path, "w")
data = 3/0  # Tried dividing by zero. Raised ZeroDivisionError
f.write(data)
f.close()

, , . (CPython , , )

A , , :

with open(path, "w") as f:
    data = 3/0  # Tried dividing by zero. Raised ZeroDivisionError
    f.write(data)
# In here the file is already closed automatically, no matter what happened.

with . : threading.Lock()

lock = threading.Lock()
with lock:  # Lock is acquired
   do stuff...
# Lock is automatically released.

, , try: ... finally: ..., , , __enter__ __exit__. .


__enter__() __exit__() .

__enter__() , , __exit__(), ( __exit__(), )

contextlib. .

+6

All Articles