nonlocal

Date: January 6th 2016
Last updated: January 6th 2016

The last of the keywords unknown to me is nonlocal. Using import keyword \n keyword.kwlist in the python (2.7.11) shell shows that nonlocal is not an available statement. The ability to change a nonlocal variable was introduced in python 3x.

The nonlocal statement in py3x lets you access a variable that is in an outer, non-global, scope. The implementation of nonlocal is similar to global in that a variable can be pulled in from an outer scope.

The following example is an annotated version of Anon's response on stackoverflow http://stackoverflow.com/questions/1261875/python-nonlocal-statement

# global variable
x = 0 

# use nonlocal and global 
def outer():
    """
    This function creates a non-global outer scope that contains 
    a nested 'inner' function. 

    prints x variable.
    """

    # outer scope variable
    x = 1 # reminder: this does not change global x 

    def inner():
        """
        This function creates a local scope inside the 
        'outer' function. If you uncomment nonlocal or global
        statements, then any changes to x in the local scope 
        will also happen to the outer or global scopes. 

        prints x variable.
        """
        # nonlocal x #uncomment to change outer scope
        # global x #uncomment to change global scope

        # local scope variable
        # if nonlocal or global is used here, 
        # changes to x will take affect
        x = 2  

        # print local scope x 
        print("inner:", x)
        # Output
        # local x is always 2!

    inner()
    # print outer scope x
    print("outer:", x)
    # Output
    # outer x can be either 1 (unchanged) or 2 (changed)

outer()
# print global scope x
print("global:", x)
# Output
# global x can be either 0 (unchanged) or 2 (changed)

""" 
Note
The final output for pre-existing bindings of x in the "outer" 
and "global" scopes only changes if the variable is pulled 
into the local scope (the 'inner' function) and updated.
"""

The only warnings that I can see from my initial search is to make sure that the nonlocal statement refers to a pre-existing binding, and the arguments do not conflict with bindings in the local scope.

For more information

!#bin/python3.4
help("nonlocal")

Useful resources:

results matching ""

    No results matching ""