Scope problem with nested functions.

AddisonN at iti-ab.com AddisonN at iti-ab.com
Thu Oct 13 05:29:32 EDT 2005


Thanks Fredrik, that's fixed it. Apologies for the lazy typing - should
have cut and pasted the whole thing.

-----Original Message-----
From: Fredrik Lundh [mailto:fredrik at pythonware.com] 
Sent: 13 October 2005 08:55
To: python-list at python.org
Subject: Re: Scope problem with nested functions.

<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, I
get:

Traceback (most recent call last):
  File "script.py", line 19, in ?
    parseFile(0, 0, 0)
  File "script.py", line 17, in parseFile
    getCcyMappings()
  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.

</F> 






**********************************************************************
This email and any files transmitted with it are confidential and
intended solely for the use of the individual or entity to whom they
are addressed. If you have received this email in error please notify
the system manager.
This footnote also confirms that this email message has been swept by
MIMEsweeper for the presence of computer viruses.
Information Technology International (ITI) +44 (0)20 7315 8500
**********************************************************************




More information about the Python-list mailing list