Skip to main content
nonlocal

nonlocal

8.2
A Python keyword used inside a function to change an outer variable
  • other
  • Specialized
translation icon : no local
  • The nonlocal keyword allows you to modify a variable from an enclosing function in Python.

Examples

  • Without nonlocal, the assignment would create a new local variable instead of modifying the outer one.

  • If you want to change a variable defined outside the inner function, use nonlocal.

  • The variable is defined as nonlocal.

  • You must declare the variable as nonlocal to modify it.

  • The nonlocal keyword is required when you want to alter a variable from an outer function within a nested definition in Python.

  • To access a variable from the nearest enclosing scope, you can use the nonlocal statement in your nested function.

  • By declaring a variable as nonlocal, you enable the inner function to modify it rather than creating a new local instance.

Surface Forms

nonlocal main

Morphology

nonlocal = local (semi-transparent) = non + local

The keyword is morphologically 'non-' + 'local', but its precise meaning as a Python reserved word (referring to variables in an enclosing non-global scope) is a programming-specific interpretation that learners need technical knowledge to apply.

Etymology

Nonlocal as a Python keyword uses non- 'not' and local 'inside this function' to mean a name is 'not local' to the inner function but belongs to the nearest outer function, so the inner code can change that variable.