[Python-ideas] A different kind of context manager
Kristján Valur Jónsson
kristjan at ccpgames.com
Wed Oct 23 16:51:05 CEST 2013
Ah, I forgot about the changed flow control with “return”, “break”, “continue”.
The decorator way does not allow that. A special “block” callable would be needed, with special return opcodes.
K
From: Kristján Valur Jónsson
Sent: 23. október 2013 14:48
To: 'Antony Lee'; python-ideas at googlegroups.com
Cc: python-ideas at python.org
Subject: RE: [Python-ideas] A different kind of context manager
Nice suggestion. And I can also do:
def _():
do_stuff()
result = execute_subprocess(_)
i.e. just do it manually, rather than with the decorator.
Your suggestion, though, is actually not such a bad pattern, but it has a few drawbacks:
1) You need the “nonlocal” qualifier to pass values out of it
2) It has the side effect of setting _
3) It is a bit non-intuitive, particularly when decorators start taking arguments. When is the decorator run? This is not always immediately clear. Well, it is simpler than a regular decorator, since it will invoke the target function itself…
4) The syntax is not nice.
Decorators themselves were invented as syntactic sugar to get rid of the
def foo():
…
foo = bar()
pattern. Maybe I should revise my suggestion then? A new syntax that does the above, i.e.:
new_with cm as bar: # or whatever keyword is deemed appropriate.
do_stuff()
compiles to:
@cm
def _( _bar):
pragma(“nonlocal”, 1) # moves binding one step upwards
bar = _bar
do_stuff()
But with _ and _bar magically hidden.
The only thing really needed, then is the support for “pragma(“nonlocal”, 1)” or an equivalent way of changing the default binding of variables, and compiler magic for syntax.
K
From: Antony Lee [mailto:anntzer.lee at gmail.com]
Sent: 22. október 2013 00:18
To: python-ideas at googlegroups.com<mailto:python-ideas at googlegroups.com>
Cc: python-ideas at python.org<mailto:python-ideas at python.org>; Kristján Valur Jónsson
Subject: Re: [Python-ideas] A different kind of context manager
You can get the desired behavior by (ab)using function decorators, by rewriting
with as_subprocess():
do_stuff()
as
@as_subprocess
def _():
<do stuff>
Yes, it's not very elegant syntactically but gets the work done (and this technique is generalizable to most uses of Ruby-style blocks, I believe).
Antony
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20131023/4abe3217/attachment.html>
More information about the Python-ideas
mailing list