GvR wrote: > [Nick Coghlan] > > Option 2: mimic if semantics > > An 'else' clause on a block statement behaves vaguely like the else clause on > > an if statement - the clause is executed only if the first suite is never > > entered, but no exception occurs (i.e. StopIteration is raised by the first call > > to next). > > Strange because it's different from the behavior of a for loop, and > the block-statement doesn't feel like an if-statement at all. But I > could actually imagine a use case: when acquiring a lock with a > time-out, the else-clause could be executed when the acquisition times > out. > > block locking(myLock, timeout=30): > ...code executed with lock held... > else: > ...code executed if lock not acquired...
A file-closing block function has the same need, as does any block function that manages a resource, whose acquisition might fail. A surrounding try/except doesn't quite cut it; the problem is that the try-clause will then also cover the suite. Example: try: in opening('file1') as f1: ... in opening('file2') as f2: ... except IOError: print "file1 not available, I'll try again later" How do I tell try/except that I really only meant to trap opening('file1'), but opening 'file2' is not supposed to fail so I want any exception from that propagated? Better if I could write: in opening('file1') as f1: ... in opening('file2') as f2: ... else: print "file1 not available, I'll try again later" or even in opening('file1') as f1: ... in opening('file2') as f2: ... except IOError: print "file1 not available, I'll try again later" I rather like this version, because it is patently clear what should happen if there is no except-clause: The exception propagates normally. - Anders _______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com