setting variables in outer functions

Steven Bethard steven.bethard at gmail.com
Mon Oct 29 19:31:56 EDT 2007


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.

STeVe



More information about the Python-list mailing list