def nested(label)print(labelstatereturn nested referencing nonlocals works normally remembers state in enclosing scope tester( ('spam'spam ('ham'ham changing name in an enclosing def' scope is not allowed by defaultthoughthis is the normal case in as welldef tester(start)state start def nested(label)print(labelstatestate + return nested cannot change by default (never in xf tester( ('spam'unboundlocalerrorlocal variable 'statereferenced before assignment using nonlocal for changes nowunder xif we declare state in the tester scope as nonlocal within nestedwe get to change it inside the nested functiontoo this works even though tester has returned and exited by the time we call the returned nested function through the name fdef tester(start)state start def nested(label)nonlocal state print(labelstatestate + return nested tester( ('spam'spam ('ham'ham ('eggs'eggs each call gets its own state remembers state in enclosing scope allowed to change it if nonlocal increments state on each call as usual with enclosing scope referenceswe can call the tester factory (closurefunction multiple times to get multiple copies of its state in memory the state object in the enclosing scope is essentially attached to the nested function object returnedeach call makes newdistinct state objectsuch that updating one function' state won' impact the other the following continues the prior listing' interaction scopes