For review: PEP 343: Anonymous Block Redux and Generator Enhancements

Andrew Dalke dalke at dalkescientific.com
Fri Jun 3 16:58:31 EDT 2005


Nicolas Fleury wrote:
> What about making the ':' optional (and end implicitly at end of current 
> block) to avoid over-indentation?
> 
> def foo():
>      with locking(someMutex)
>      with opening(readFilename) as input
>      with opening(writeFilename) as output
>      ...
>
> would be equivalent to:
> 
> def foo():
>      with locking(someMutex)
>          with opening(readFilename) as input
>              with opening(writeFilename) as output
>                  ...

Nothing in Python ends at the end of the current block.
They only end with the scope exits.  The order of deletion
is not defined, and you would change that as well.

Your approach wouldn't allow the following

with locking(mutex):
  increment_counter()

x = counter()

with locking(mutex):
  decrement_counter()

 
except by making a new block, as

if 1:
  locking(mutex)

  x = counter()

if 1:
  locking(mutex)


If the number of blocks is a problem it wouldn't be that
hard to do

with multi( locking(someMutex),
            opening(readFilename),
            opening(writeFilename) ) as _, input, output:
  ...

Untested sketch of an implementation


class multi(object):
  def __init__(self, *args):
    self.args = args
  def __enter__(self):
    results = []
    for i, arg in enumerate(self.args):
      try:
        results.append(arg.__enter__())
      except:
        # back up through the already __entered__ args
        exc = sys.exc_info()
        for j in range(i-1, -1, -1):
          try:
            self.args[j].__exit__(*exc)
          except:
            # Need to get the new exception, to match the PEP behavior
            exc = sys.exc_info()
        raise exc[0], exc[1], exc[2]
    return results

  def __exit__(self, type, value, traceback):
    for arg in self.args[::-1]:
      try:
        arg.__exit__(type, value, traceback)
      except:
        type, value, traceback = sys.exc_info()

				Andrew
				dalke at dalkescientific.com




More information about the Python-list mailing list