A "scopeguard" for Python

Alf P. Steinbach alfps at start.no
Fri Mar 5 14:09:08 CET 2010

* Robert Kern:
> 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."

Oh yes, in the article where I gave the example of that, shown above.

Hey, discussing previous discussion is silly.


- ALf

More information about the Python-list mailing list