block/lambda
Jean-Paul Calderone
exarkun at divmod.com
Tue Jul 29 10:47:53 EDT 2008
On Tue, 29 Jul 2008 07:26:38 -0700 (PDT), "jiri.zahradil at gmail.com" <jiri.zahradil at gmail.com> wrote:
>
>> 2. Will it be possible in Python 3.0 to do the following:
>>
>> >>> def dotimes(n, callable):
>>
>> for i in range(n): callable()
>>
>> >>> def block():
>>
>> nonlocal i
>> for j in range(i):
>> print j,
>> print
>
>dotimes seems ok and what is wrong with that function "block"? You do
>not need to specify that i is "nonlocal", global i will be used.
>
>>>> i=10
>>>> def block():
> for j in range(i):
> print j,
> print
>>>> block()
>0 1 2 3 4 5 6 7 8 9
>
Python doesn't have dynamic scoping.
>>> def dotimes(n, callable):
... for i in range(n):
... callable()
...
>>> def block():
... for j in range(i):
... print j,
... print
...
>>> def f():
... dotimes(5, block)
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in f
File "<stdin>", line 3, in dotimes
File "<stdin>", line 2, in block
NameError: global name 'i' is not defined
>>>
The "nonlocal" keyword in Python 3 won't do this, either. It's for
referencing names in outer lexical scopes, not outer dynamic scopes.
Jean-Paul
More information about the Python-list
mailing list