I have found blocks of code like this:
with a as b:
c = b.algo()
It would look like some dynamic 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 for with
, and how does it work? What is the role of __exit__
?
The clause
with
does not have in python the function of delimiting the namespace ( "namespaces" ) as it is done in other languages such as VB. It's more for determining the locale that a block of code will have, which is known as "context" .A "context" is basically set with an initial setup and an end to retrieve the previous values. An example would be opening a file:
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, "context managers" ( "context manager" ) are used, which are objects that have the methods
__enter__
and__exit__
. The first to initialize the context, the second to end it.Objects in python implement the context manager
files
interface , so using them in contexts will ensure that files are 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:There are also libraries, such as fabric , that use the contexts to configure the connections of the servers on which to execute a script.
In your case, the error you get is that the variable does not have the context manager
a
methods defined .For more detailed information, see the PEP-343