finallyif you are not using python and don' have nonlocal statement--or you want your code to work portably on both and --you may still be able to avoid globals and classes by making use of function attributes for some changeable state instead in all pythons since we can assign arbitrary attributes to functions to attach themwith func attr=value because factory function makes new function on each callits attributes become per-call state moreoveryou need to use this technique only for state variables that must changeenclosing scope references are still retained and work normally in our examplewe can simply use wrapper calls for state the following works the same as the preceding nonlocal version because the counter is again per-decoratedfunctionbut it also runs in python xdef tracer(func)state via enclosing scope and func attr def wrapper(*args**kwargs)calls is per-functionnot global wrapper calls + print('call % to % (wrapper callsfunc __name__)return func(*args**kwargswrapper calls return wrapper @tracer def spam(abc)print( csame asspam tracer(spam@tracer def eggs(xy)print( *ysame aseggs tracer(eggsspam( spam( = = = really calls wrapperassigned to spam wrapper calls spam eggs( eggs( = really calls wrapperassigned to eggs wrapper calls _is_ per-decoration here as we learned in this works only because the name wrapper is retained in the enclosing tracer function' scope when we later increment wrapper callswe are not changing the name wrapper itselfso no nonlocal declaration is required this version runs in either python linec:\codepy - decorator py same output as prior versionbut works on too this scheme was almost relegated to footnotebecause it may be more obscure than nonlocal in and might be better saved for cases where other schemes don' help howeverfunction attributes also have substantial advantages for onethey allow access to the saved state from outside the decorator' codenonlocals can only be seen inside the nested function itselfbut function attributes have wider visibility for anotherthey are far more portablethis scheme also works in xmaking it versionneutral decorators