ENH: Implement support for with-blocks.#59
Conversation
The basic idea here is rewrite the ast of the with-block into two
statements and try-except, which we already know how to oneline-ify
In general, we can rewrite a with block of the form:
with <expr> as <ctxname>:
<body>
as
__anonymous = <expr>
<ctxname> = __anonymous.__enter__()
try:
<body>
except:
if not __anonymous.__exit__(*sys.exc_info()):
raise
else:
__anonymous.__exit__(None, None, None)
7285071 to
942b45d
Compare
There was a problem hiding this comment.
These were needed because I'm inserting assignments to names that weren't in the original source, which means they aren't in the symbol table.
|
Thanks for looking at this. Sequencing subsequent statements is the purpose of the Have you read PEP 343? It gives a slightly different translation of the In general, I think it would be better to factor out the Such refactoring could also tremendously simplify the resulting translated code. For example, the |
|
@andersk thanks for the thorough read-through. Responses to notes in line:
Ah, that's a good point. I hadn't considered jumping out of the with block from a loop.
Makes sense as well.
I'm not sure what you mean here. Are you just suggesting that we replace the big nested AST literals with easier-to-read/change functions? Or do you think the strategy of doing AST-level writing itself is the wrong way to do this. My experience has been that it's significantly easier to do source-to-source transformations on AST trees than on raw strings |
|
I’m explaining our reasons to avoid AST-level rewriting, yes. Perhaps things would be different if as something more like Some examples of this pattern already in use are |
I missed the presentation tonight at Boston Python, but a colleague pointed me at this repository.
This PR is a work in progress toward support for with-blocks.
The basic idea here is rewrite the ast of the with-block into two
statements and a try-except, which we already know how to oneline-ify
In general, we can rewrite a with block of the form:
as
Once we've rewritten the AST, we should be able to just delegate to existing the existing functionality for sequencing statements and handling try-except blocks.
This mostly works as-is, but for reasons I don't quite understand, statements after the with-block aren't being executed. I suspect that I'm not correctly doing whatever work is needed to sequence the with-block with subsequent statements. Any guidance here would be appreciated.