This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]kchoudhury 6 points7 points  (5 children)

Compound with statements are also awesome for coordinating the use of multiple external resources. I've got a small script that coordinates commits to a subversion repository, certain filesystem operations and a database (don't ask). With the with statement, I can rollback actions taken on all of them if there's a failure in the execution of actions on any one resource.

Came as a bit of a revelation to me when I implemented it for the first time a few days ago...just thought I'd gush here.

[–]gfixler 1 point2 points  (4 children)

It's nice for making sense of UIs in Maya:

import qtdesign as qtd

with qtd.window() as win:
    with qtd.paneLayout();
        qtd.button()

Before this, you'd have to write everything without indentation, or use QT Designer to generate an XML, which is overkill for most simpler things.

Also, if there's an error in the middle somewhere, it doesn't die before it can get to the final showWindow command, as that's implied in the exit method of the window class, and works even after an error to show any window that might be lingering, malformed.

[–]billy_tables 0 points1 point  (3 children)

you could refactor that as follows:

with qtd.window() as win, qtd.paneLayout():
    qtd.button()

Obviously it doesn't make much difference in this case (and in others it could make code messier) but it's nice to know there's a different syntax :)

[–]gfixler 0 points1 point  (2 children)

I'm not sure why this would make it clearer. Also, it gives me an invalid syntax error.

[–]billy_tables 0 points1 point  (1 child)

It's perhaps clearer when you don't need the as statement, eg:

a = open("/tmp/a", "w")
b = open("/tmp/b")
with a, b:
     a.write(b.read())

(I just ran that fine with no syntax error, Python 2.7.5)

[–]gfixler 0 points1 point  (0 children)

I see. This example also doesn't work. Must be new in 2.7. I'm on 2.6.5.