coworkerswill generally be better if you minimize nested function definitions the nonlocal statement in in the prior section we explored the way that nested functions can reference variables in an enclosing function' scopeeven if that function has already returned it turns out thatin python (though not in )we can also change such enclosing scope variablesas long as we declare them in nonlocal statements with this statementnested defs can have both read and write access to names in enclosing functions this makes nested scope closures more usefulby providing changeable state information the nonlocal statement is similar in both form and role to globalcovered earlier like globalnonlocal declares that name will be changed in an enclosing scope unlike globalthoughnonlocal applies to name in an enclosing function' scopenot the global module scope outside all defs also unlike globalnonlocal names must already exist in the enclosing function' scope when declared--they can exist only in enclosing functions and cannot be created by first assignment in nested def in other wordsnonlocal both allows assignment to names in enclosing function scopes and limits scope lookups for such names to enclosing defs the net effect is more direct and reliable implementation of changeable state informationfor contexts that do not desire or need classes with attributesinheritanceand multiple behaviors nonlocal basics python introduces new nonlocal statementwhich has meaning only inside functiondef func()nonlocal name name ok here nonlocal syntaxerrornonlocal declaration not allowed at module level this statement allows nested function to change one or more names defined in syntactically enclosing function' scope in python xwhen one function def is nested in anotherthe nested function can reference any of the names defined by assignment in the enclosing def' scopebut it cannot change them in xdeclaring the enclosing scopesnames in nonlocal statement enables nested functions to assign and thus change such names as well this provides way for enclosing functions to provide writeable state informationremembered when the nested function is later called allowing the state to change makes it more useful to the nested function (imagine counter in the enclosing scopefor instancein xprogrammers usually achieve similar goals by using classes or scopes