PEP 310 suggestions

Ben ben at transversal.com
Wed Jan 7 04:27:42 EST 2004


I hope its not too late to make these comments as I know the PEP has been
around for a while!

I've just been reading PEP 310 and have found it very interesting, as the
problem it attepts to solve is one of the few things I find annoying about
languages like python (coming from a C++ background). 

It would have been nice to be about to use __init__ and __del__ pairs, but
having read the discussion I see that this would be effectively
immpossible.

While I was reading the PEP a few ideas popped into my head and I wondered
if something like them had already been considered. They are probably
rubbish, but I thought I would throw them into the mix!

1) If Python had code blocks, something like this would be possible

def open_file(file, code_block):
  try:
        code_block()
  finally:
        file.close()

then,

f = file("foo")
with open_file(f):     #Note only passing one argument
  # do stuff with f

This would only work if the code_block could be executed in the scope in
which it was written, and not in the one in which it was called. 

This seems to be more general than the current PEP, but introduces quite
massive changes into the language. The idea is that:

with func(args):
        suite

goes to

func(args, suite)

2) Exit handler blocks. These are kind to backwards try-finally blocks that
allow the "close" function to be written close to the "open" one. They also
have the advantage that no extra special functions are needed.

e.g

l = lock.aquire()
onexit l.release():
  # do stuff while locked

is eqivalent to

l = lock.aquire()
try:
   # do stuff while locked
finally:
   l.release()

The obvious disadvantage is that it may be non-obvious that the release call
is delayed to the end of the block

Any comments? The main reason I like these methods is that they are both
more explicit than the PEP, and don't require the addition of any more
special functions. However I can see the disadantages as well!


Cheers

Ben
---



More information about the Python-list mailing list