On 11/14/2019 12:53 PM, Richard Damon wrote:

On Nov 14, 2019, at 12:20 PM, R.Wieser <address@not.available> wrote:

MRAB,

'nonlocal' is used where the function is nested in another function

The problem is that that was not clear to me from the description - nor is
it logical to me why it exludes the main context from its use.

Regards,
Rudy Wieser

Module ‘main’ content is already available via ‘global’, nonlocal was likely 
added later to get to enclosing function scope, which isn’t global, nor is it 
local.

Correct, and the addition was in two stages. At first, automatically *accessing* non-locals was added. Note that no declaration is needed, just as no declaration is needed to access globals.

>>> >>> f(3)
3

The 'nonlocal' keyward to *rebind* nonlocals, analogous to the 'global' keyword to rebind module globals, was added later, for 3.0, after considerable bikeshedding on the new keyword.

The access mechanism is quite different. Function f accesses globals through f.__globals__, which points to the global dict. In CPython, at least, it accesses nonlocals through f.__closure__, a tuple of 'cells'.

>>> def f(a):
        b = 'b outer'
        def g():
                nonlocal b
                print(a, b)
                b = 'b inner'
                print(a, b)
        print(g.__closure__)
        g()

        
>>> f(0)
(<cell at 0x00000277AAA90910: int object at 0x00007FFD9ACC9680>, <cell at 0x00000277AAAF7880: str object at 0x00000277AAB0DAB0>)
0 b outer
0 b inner
>>> print(f.__closure__)
None

Closures are used in functional programs, instead of classes, to create 'groups' of functions than share 'group' variables.

--
Terry Jan Reedy


--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to