[Python-ideas] Defer Statement
Nick Coghlan
ncoghlan at gmail.com
Sat Jun 3 08:24:33 EDT 2017
On 3 June 2017 at 20:59, Daniel Bershatsky <bepshatsky at yandex.ru> wrote:
> Dear Python Developers,
>
> We have a potential idea for enhancing Python. You will find a kind of draft
> bellow.
Thank you for taking the time to write this up!
> Best regards,
> Daniel Bershatsky
>
>
> Abstract
> ========
>
> This PEP proposes the introduction of new syntax to create community
> standard,
> readable and clear way to defered function execution in basic block on all
> control flows.
>
> Proposal
> ========
>
> There is not any mechanism to defer the execution of function in python.
There is, thanks to context managers:
import contextlib
def foo(i):
print(i)
def bar():
with contextlib.ExitStack() as stack:
stack.callback(foo, 42)
print(3.14)
bar()
Now, defer is certainly pithier, but thanks to contextlib2, the above
code can be used all the way back to Python 2.6, rather than being
limited to running on 3.7+. I was also motivated enough to *write*
ExitStack() to solve this problem, but even I don't use it often
enough to consider it worthy of being a builtin, let alone syntax.
So while I'm definitely sympathetic to the use case (otherwise
ExitStack wouldn't have a callback() method), "this would be useful"
isn't a sufficient argument in this particular case - what's needed is
a justification that this pattern of resource management is common
enough to justify giving functions an optional implicit ExitStack
instance and assigning a dedicated keyword for adding entries to it.
Alternatively, the case could be made that there's a discoverability
problem, where folks aren't necessarily being pointed towards
ExitStack as a dynamic resource management tool when that's what they
need, and to consider what could be done to help resolve that (with
adding a new kind of statement being just one of the options
evaluated).
Cheers,
Nick.
P.S. Nikolas Rauth has a more in-depth write-up of the utility of
ExitStack here:
https://www.rath.org/on-the-beauty-of-pythons-exitstack.html
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas
mailing list