[Python-Dev] Extended Function syntax

Guido van Rossum guido@python.org
Sun, 02 Feb 2003 14:34:15 -0500


[Samuele]
> yes, real-world examples would be good.

synchronized() is definitely a real-world example -- writing
try/finally for locks is a pain for all threaded code.

Another, related example would be something that blocks all signals
(or at least SIGINT) during a certain code block.

I imagine that there are quite a few examples that basically wrap a
code block in something that does some preparation and some cleanup.

These require that the cleanup action is done even if an exception
occurred in the block, and this can't be done with the "for loop" hack
proposed by Armin (unless you rely on __del__, which would be a no-no
for Jython).

'do' or 'with' should be up to this task.

I'm now wondering if there aren't really only two interesting cases,
none of which require saving the thunk and calling it later:

- synchronized-like, where the block should connect to its environment

- property-like, where the block should introduce a new scope, and the
  caller should be able to inspect or control that scope's namespace

All cases where something is saved to be called later can be done
by using the extended 'def' syntax (def f(...) [something]: ...).

I think that for synchronized-like cases, even if it is known at
compile time that it is to be part of the surrounding scope, the code
generated will still need to use nested-scope-cells, since it will be
invoked on a different stack frame: the "thunk processor" pushes its
own frame on the stack, and I think you can't have something that
executes in a frame that's not the topmost frame.  (Or can you?  I
don't know exactly what generators can get away with.)

--Guido van Rossum (home page: http://www.python.org/~guido/)