Jump to content

Non-local variable

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Ruud Koot (talk | contribs) at 11:29, 16 September 2011 (not is it global). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In programming language theory, a non-local variable is a variable that is not defined in the local scope. While the term can refer to global variables, it is primarily used in the context of nested and anonymous functions where can some variable can be neither in the local nor in the global scope.

Example

In the example that follows there is a nested function inner defined in the scope of another function outer. The variable is local to outer, but non-local to inner (nor is it global):

def outer():
    x = 1
    def inner():
        nonlocal x
        x += 1
        print(x)
    return inner

In this example the variable c is non-local in the anonymous function \x -> x + c:

outer = let c = 1 in map (\x -> x + c) [1, 2, 3, 4, 5]

See also