Uplevel functionality

Terry Reedy tjreedy at udel.edu
Wed Dec 31 12:41:02 EST 2003


"Maciej Sobczak" <no.spam at no.spam.com> wrote in message
news:bsu3bu$5rm$1 at nemesis.news.tpi.pl...
> Hello,
>
> I would like to know if there is any possibility in Python to execute
> arbitrary scripts in the context higher in the stack frame.

An alternate answer from those already posted is to not create the new
context that you want to uplevel from.  Seriously.

>  In essence, I would like to have the equivalent of the following Tcl
code:
>
> proc repeat {n script} {
> for {set i 0} {$i < $n} {incr i} {
> uplevel $script
> }
> }

As I read this, this defines the repeat function as an abbreviation of a
'for' loop.  The uplevel is only needed because the abbreviating process
creates a nested frame.  In Lisp, repeat would be written a text macro
which does the substitution in the same frame, and hence the frame problem
and need for uplevel would not arise.  In Python, we currently live without
the pluses and minuses of macros and usually write out the for loops ;-)

> This allows me to do:
>
> repeat 5 {puts "hello"}
>
> prints:
> hello
> hello
> hello
> hello
> hello

for i in range(5): print 'hello' # does same thing.
repeat(5, "print 'hello'")       # even if possible, saves all of 5 key
strokes
repeat(5, lambda: print 'hello') # possible, without uplevel, takes 2 more

> Or this:
>
> set i 10
> repeat 5 {incr i}
> puts $i
>
> prints:
> 15

i=10
for n in range(5): i+=1
print i

In batch mode, which requires 'print ', 36 instead of 33 keystrokes.

You *can* do this in current Python:

def repeat(num, func):
   for i in range(num): func()

def inci(): i[0]+=1 # need def since lambda only abbreviates 'return
expression'

i=[10]
repeat(5, inci)
>>> print i[0]
15

Python goes for clarity rather than minimal keystrokes.  Example:
It has been proposed that 'for i in n:' be equivalent to 'for i in
range(n):'.
Given the set theory definition n == {0, ..., n-1} (==set(range(n))),
this is theoretically sensible, but was judged too esoteric for most
people.

Terry J. Reedy






More information about the Python-list mailing list