syntaxerrorno binding for nonlocal 'spamfound these restrictions make sense once you realize that python would not otherwise generally know which enclosing scope to create brand-new name in in the prior listingshould spam be assigned in testeror the module outsidebecause this is ambiguouspython must resolve nonlocals at function creation timenot function call time why nonlocalstate retention options given the extra complexity of nested functionsyou might wonder what the fuss is about although it' difficult to see in our small examplesstate information becomes crucial in many programs while functions can return resultstheir local variables won' normally retain other values that must live on between calls moreovermany applications require such values to differ per context of use as mentioned earlierthere are variety of ways to "rememberinformation across function and method calls in python while there are tradeoffs for allnonlocal does improve this story for enclosing scope references--the nonlocal statement allows multiple copies of changeable state to be retained in memory it addresses simple stateretention needs where classes may not be warranted and global variables do not applythough function attributes can often serve similar roles more portably let' review the options to see how they stack up state with nonlocal only as we saw in the prior sectionthe following code allows state to be retained and modified in an enclosing scope each call to tester creates self-contained package of changeable informationwhose names do not clash with any other part of the programdef tester(start)state start def nested(label)nonlocal state print(labelstatestate + return nested each call gets its own state remembers state in enclosing scope allowed to change it if nonlocal tester( ('spam'state visible within closure only spam state attributeerror'functionobject has no attribute 'statewe need to declare variables nonlocal only if they must be changed (other enclosing scope name references are automatically retained as usual)and nonlocal names are still not visible outside the enclosing function scopes