releasesbut most have been known to trip up new users local names are detected statically as you knowpython classifies names assigned in function as locals by defaultthey live in the function' scope and exist only while the function is running what you may not realize is that python detects locals staticallywhen it compiles the def' coderather than by noticing assignments as they happen at runtime this leads to one of the most common oddities posted on the python newsgroup by beginners normallya name that isn' assigned in function is looked up in the enclosing modulex def selector()print(xx used but not assigned found in global scope selector( herethe in the function resolves to the in the module but watch what happens if you add an assignment to after the referencedef selector()print(xx does not yet existx classified as local name (everywherecan also happen for "import ""def xselector(unboundlocalerrorlocal variable 'xreferenced before assignment you get the name usage error shown herebut the reason is subtle python reads and compiles this code when it' typed interactively or imported from module while compilingpython sees the assignment to and decides that will be local name everywhere in the function but when the function is actually runbecause the assignment hasn' yet happened when the print executespython says you're using an undefined name according to its name rulesit should say thisthe local is used before being assigned in factany assignment in function body makes name local imports=nested defsnested classesand so on are all susceptible to this behavior the problem occurs because assigned names are treated as locals everywhere in functionnot just after the statements where they're assigned reallythe previous example is ambiguouswas the intention to print the global and create local xor is this real programming errorbecause python treats as local everywhereit' seen as an errorif you mean to print the global xyou need to declare it in global statementdef selector()global print(xx force to be global (everywherefunction gotchas