Could Emacs be rewritten in Python?
Robin Munn
rmunn at pobox.com
Tue Apr 15 17:30:25 EDT 2003
Alex Martelli <aleax at aleax.it> wrote:
> Robin Munn wrote:
> ...
>> How is try ... finally "broken and fragile code"? How is this:
>>
>> try:
>> old_stdout = sys.stdout
>> new_stdout = cStringIO.StringIO()
>> sys.stdout = new_stdout
>> function_whose_output_I_want_to_capture()
>> do_something_with(new_stdout)
>> finally:
>> sys.stdout = old_stdout
>>
>> in any way inferior to this (making up a semi-Pythonic syntax):
>>
>> with sys.stdout = cStringIO.StringIO():
>> function_whose_output_I_want_to_capture()
>> do_something_with(sys.stdout)
>>
[snip...]
>>
>> What I really want to know is why you would consider sample #1 "broken
>> and fragile code". I can't think of any circumstances where sample #1
>> would fail to achieve its desired effect. Can you?
>
[snip...]
>
> Another difference between the two snippets, which I don't
> understand, comes when function_blah_blah does its own rebinding
> of sys.stdout. In that case, the first snippet "ignores" the
> rebinding (calls do_something_with with the value you had just
> bound to sys.stdout BEFORE calling function_blahblah), the
> second snippet "accepts" the rebinding (calls do_etc with the
> value CURRENTLY bound to sys.stdout). Since I don't know what's
> SUPPOSED to be happening under such circumstances, I can't tell
> which of the two versions (if either) is wrong, but I do find
> the difference puzzling. Assuming the second hypothetical snippet
> has the correct semantics, then, maybe the first one should be:
>
> old_stdout = sys.stdout
> sys.stdout = cStringIO.StringIO()
> try:
> function_whose_output_I_want_to_capture()
> do_something_with(sys.stdout)
> finally:
> sys.stdout = old_stdout
>
> to achieve the same semantics -- specifically, what we want
> to put in the try clause is just what would go in the with
> clause's body if it existed, while the "saving the previous
> state" (implicit in the hypothetical 'with') and the actual
> initialization (the assignment that follows the with keyword
> itself in the hypothetical case) need to be BEFORE the try
> clause.
You're right; using the new_stdout variable name was unnecessary and
would have rejected any sys.stdout rebinding that function_etc() might
have done.
I suppose I just illustrated how a try ... finally block might be
considered "broken and fragile". I tried to use it, and missed some
subtleties. I'm still not convinced that a "with"-like statement is
necessary in Python, but I think I just went from -1 to -0 on it.
--
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838
More information about the Python-list
mailing list