What is it for and how does the "with" keyword work in Python?

I have found blocks of code of this type:

with a as b:
    c = b.algo()

Would look like some dynamics similar to namespaces, but the following code

a = 1
with a as b:
    print a, b

Returns the following error:

AttributeError: __exit__

So what is the Keyword with for, and how does it work? What is the role of __exit__?

 13
Author: Alvaro Montoro, 2016-11-02

1 answers

The with Clause does not have in python the function of delimiting the namespace ("namespaces") as is done in other languages like VB. It is more to determine the locale that a block of code will have, which is known as "context" .

A "context" is basically set with an initial setting and a completion to retrieve the previous values. An example would be the opening of a file:

with open("fichero.txt") as f:
    print(f.read())

We start the block by opening the file and, at the end, the file will be closed automatically, even if it has not been explicitly indicated.

To control a context, the "context handlers " are used" ("context manager" ) which are objects that have the __enter__ and __exit__ methods defined. The first to initialize the context, the second to end it.

Objects files in python implement the interface of context , so its use in contexts will ensure that the files will be closed correctly.

There are many more objects in the standard library that implement the context Manager interface. One of the most significant is the type Decimal, where through a context you can specify the decimal precision of the operations to be performed within the Block:

from decimal import localcontext

with localcontext() as ctx:
    ctx.prec = 42   # Precisión de 42 cifras significativas
    s = calculate_something() # cálculo de alta precisión

s = +s  # regreso a la precisión por defecto del tipo decimal

There are also libraries, such as fabric , that use contexts to set the configuration of the connections of the servers on which to run a script.

In your case, the error it gives you is that the variable a does not have defined the methods of context manager.

For more detailed information, look at the PEP-343

 16
Author: ChemaCortes, 2016-11-03 00:15:56