A "scopeguard" for Python

Robert Kern robert.kern at gmail.com
Thu Mar 4 22:42:32 EST 2010


On 2010-03-04 16:27 , Alf P. Steinbach wrote:
> * Mike Kent:

>> However, I fail to understand his response that I must have meant try/
>> else instead, as this, as Mr. Kern pointed out, is invalid syntax.
>> Perhaps Mr. Steinbach would like to give an example?
>
> OK.
>
> Assuming that you wanted the chdir to be within a try block (which it
> was in your code), then to get code equivalent to my code, for the
> purpose of a comparision of codes that do the same, you'd have to write
> something like ...
>
> original_dir = os.getcwd()
> try:
> os.chdir(somewhere)
> except Whatever:
> # E.g. log it.
> raise
> else:
> try:
> # Do other stuff
> finally:
> os.chdir(original_dir)
> # Do other cleanup
>
> ... which would be a more general case.
>
> I've also given this example in response to Robert earlier in the
> thread. Although I haven't tried it I believe it's syntactically valid.
> If not, then the relevant typo should just be fixed. :-)
>
> I have no idea which construct Robert thought was syntactically invalid.
> I think that if he's written that, then it must have been something he
> thought of.

I was just trying to interpret what you meant by "Changing 'finally' to 'else' 
could make it equivalent." As far as I can tell, that has only one possible 
interpretation going by the plain meaning of the words, and it isn't yours. 
Since you always seem to refer to "try/else" as if it were an independent 
construct and not part of "try: except: else:" and no one else introduced 
except: clause, I must reiterate that your communications have been fabulously 
misleading.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list