Python is readable

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Thu Mar 15 11:41:36 EDT 2012


Am 15.03.2012 12:48 schrieb Kiuhnm:
> On 3/15/2012 12:14, Thomas Rachel wrote:
>> Am 15.03.2012 11:44 schrieb Kiuhnm:
>>
>>> Let's try that.
>>> Show me an example of "list comprehensions" and "with" (whatever they
>>> are).
>>
>> with open("filename", "w") as f:
>> f.write(stuff)
>
> Here f is created before executing the block and destroyed right after
> leaving the block. f's destructor will probably close the file handle.

No, that is the point here: with calls __enter__ on entry and __exit__ 
on, well, exit.

In the case of files, __enter__ doesn't probably do anything special, 
but returns the object again in order to be assigned to f. In __exit__, 
the file is closed.

with open("/tmp/filename", "w") as f:
     print f
print f

<open file '/tmp/filename', mode 'w' at 0xb74e6d30>
<closed file '/tmp/filename', mode 'w' at 0xb74e6d30>

So after the with clause, f is actually closed, but still present as object.

>> with lock:
>> do_something_exclusively()

> It's clear what it does, but I don't know if that's special syntax.

If you call "with" special syntax, it is.

> Maybe objects can have two special methods that are called respect. on
> entering and leaving the with-block.

Exactly, see above.

Here, on entry __enter__ is called which acquires the lock.
__exit__ releases it again.


> Or, more likely, lock creates an object which keeps the lock "acquired".
> The lock is released when we leave the block.
> So we could inspect the lock with
> with lock as l:
> inspect l...
> do_some.....

Or just inspect l - I don't know if a lock's __enter__ methos returns it 
again for assignment with "as"...


Thomas



More information about the Python-list mailing list