Uplevel functionality
Robin Becker
robin at jessikat.fsnet.co.uk
Wed Dec 31 09:54:38 EST 2003
In article <X6LEpKAqFu8$Ewln at jessikat.fsnet.co.uk>, Robin Becker
<robin at jessikat.fsnet.co.uk> writes
However, by using an exec '' the following can be made to work. The exec
is used to disable the unwanted optimisation of print k into a name
error.
##################################
def repeat(n, script):
from sys import _getframe
f = _getframe(1)
L = f.f_locals
G = f.f_globals
for i in xrange(n):
exec script in G, L
def test():
i = 0
repeat(3,'print i;i+=5')
exec ''
repeat(3,'k=2')
print k
if __name__=='__main__':
test()
##################################
>In article <bsu3bu$5rm$1 at nemesis.news.tpi.pl>, Maciej Sobczak
><no.spam at no.spam.com> writes
>
>How about this, apparently f_locals/globals are readonly so you won't be
>allowed arbitrary scopes.
>
>############################
>C:\tmp>cat repeat.py
>def repeat(n, script):
> from sys import _getframe
> f = _getframe(1)
> L = f.f_locals
> G = f.f_globals
> for i in xrange(n):
> exec script in G, L
>
>def test():
> i = 0
> repeat(3,'print i;i+=5')
>
>if __name__=='__main__':
> test()
>
>C:\tmp>repeat.py
>0
>5
>10
>
>C:\tmp>
>############################
>>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.
>>
>>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
>> }
>>}
>>
>>This allows me to do:
>>
>>repeat 5 {puts "hello"}
>>
>>prints:
>>hello
>>hello
>>hello
>>hello
>>hello
>>
>>Or this:
>>
>>set i 10
>>repeat 5 {incr i}
>>puts $i
>>
>>prints:
>>15
>>
>>That second example shows that the script provided as a second parameter
>>to the "repeat" procedure (the script is "incr i") is executed in the
>>context where the procedure was called, not locally in the procedure itself.
>>
>>The strongest analogy to the above repeat procedure in Tcl would be a
>>hypothetical Python function:
>>
>>def repeat(n, script):
>> for i in xrange(n):
>> EVALUATE script HIGHER IN THE STACK #???
>>
>>
>>Thank you very much,
>>
>
--
Robin Becker
More information about the Python-list
mailing list