setting variables in outer functions

Steven Bethard steven.bethard at gmail.com
Tue Oct 30 17:11:06 CET 2007


Neil Cerutti wrote:
> On 2007-10-29, Steven Bethard <steven.bethard at gmail.com> wrote:
>> Hrvoje Niksic wrote:
>>> Tommy Nordgren <tommy.nordgren at comhem.se> writes:
>>>
>>>> Given the following:
>>>> def outer(arg)
>>>>      avar = ''
>>>>      def inner1(arg2)
>>>>           # How can I set 'avar' here ?
>>> I don't think you can, until Python 3:
>>> http://www.python.org/dev/peps/pep-3104/
>> But it definitely does work in Python 3 if you use 'nonlocal'::
>>
>>      Python 3.0a1+ (py3k:58681, Oct 26 2007, 19:44:30) [MSC v.1310 32 bit
>>      (Intel)] on win32
>>      Type "help", "copyright", "credits" or "license" for more
>>      information.
>>      >>> def f():
>>      ...     x = 1
>>      ...     def g():
>>      ...         nonlocal x
>>      ...         x = 2
>>      ...     print(x)
>>      ...     g()
>>      ...     print(x)
>>      ...
>>      >>> f()
>>      1
>>      2
>>
>> That said, I'd like to see the reason you think you want to do
>> this.
> 
> It's allows a standard programming idiom which provides a
> primitive form of object oriented programming using closures to
> represent state.

Yeah, that's what I was afraid of. ;-)

STeVe



More information about the Python-list mailing list