What is assigned to the variable `variable`, in` with expression as variable`?

From Python training:

The basic format of the with statement looks like this: an optional part in square brackets:

with expression [as variable]: with-block 

It is assumed that expression returns an object that supports the context control protocol (more about this protocol in an instant). This object can also return a value that will be assigned to the name variable if an optional clause is present.

Note that variable not necessarily assigned the result of expression ; the result of expression is an object that supports the context protocol, or a variable may be assigned; something else is intended to be used inside the operator.

expression is evaluated by the context manager object.

What is assigned to variable ? The quote only says that it is not an object of the context manager.

Does the assignment of variable allow you to call some method of the context manager class to get the actual value assigned to variable ?

Thanks.

+8
python
source share
2 answers

Whatever is returned from __enter__ . From the documentation on the __enter__ method of __enter__ managers :

contextmanager.__enter__()

Enter the runtime context and return this object or another object associated with the runtime context. The value returned by this method is bound to the identifier in the as expression of the with statements using this context manager.

(Emphasize mine)

The result of the __enter__ call __enter__ well be a context manager, nothing in the specification prohibits this. Of course, this may be another object related to the context of the runtime, because the state of the documents.

Objects returned from __enter__ can be used again and again as context managers. file objects , for example:

 with open('test_file') as f1: # file.__enter__ returns self with f1 as f2: # use it again, get __self__ back print("Super context managing") with f2 as f3, f1 as f4: # getting weird. print("This can go on since f1.__enter__ returns f1") print("f1.__exit__ has been called here, though :)") print("f1 closed: {}".format(f1.closed)) 

Not that the previous one made sense, but simply to make it clear.

+10
source share

Your object can function as a context manager if it provides both __enter__ and __exit__ . The object returned by __enter__ is bound to the object specified in the as part of the with statement:

 In [1]: class Foo: ...: def __enter__(self): ...: return 'hello' ...: def __exit__(self, *args): ...: pass ...: In [2]: with Foo() as a: ...: print(a) ...: hello 
+8
source share

All Articles