Scope problem with nested functions.
fredrik at pythonware.com
Thu Oct 13 09:55:29 CEST 2005
<AddisonN at iti-ab.com> wrote
> I'm having trouble resolving a scope problem. I have a module,
> called from another script, with this structure:
the code you posted gives a syntax error. if I fix that, and add some
boilerplate to call getCcyMappings from inside the parseFile function,
Traceback (most recent call last):
File "script.py", line 19, in ?
parseFile(0, 0, 0)
File "script.py", line 17, in parseFile
File "script.py", line 8, in getCcyMappings
ccyMappings['CAN'] = ['CAD'] # for example.
NameError: global name 'ccyMappings' is not defined
which tells you that there is no *global* variable named ccyMappings.
the ccyMappings variable in your example isn't a global variable; it's local
to the parseFile function, and can be accessed from that function and any
inner functions via normal lexical scoping rules (=access, but not rebind).
however, the global statement tells Python that the given name is a global
variable, and that any attempts to access or rebind that variable should be
done at the global (=module) level.
if you remove the global statement, Python will look for variables using
ordinary lexical scoping, and things will work as expected.
More information about the Python-list