[Tutor] Re: Shadow error
dman
dsh8290@rit.edu
Fri, 27 Jul 2001 00:14:15 -0400
On Thu, Jul 26, 2001 at 10:34:51PM -0500, Christopher Smith wrote:
| <Untitled Script 5>:13: SyntaxWarning: local name 'm' in 'mtrx'
| shadows use of 'm' as global in nested scope 'a'
|
| def mtrx(m):
| def a(i,j):
| return m[i][j]
| return a
| l=[[1,2],[3,4]]
| a=mtrx(l)
| # no traceback unless I uncomment the next line:
| # print a(1,2)
In this example you are relying on the local (argument) 'm' from
funciton mtrx to be available inside the nested function 'a'. In old
python (pre 2.1 with a __future__ statement) scopes were not nested so
the 'm' inside 'a' would have referred to a global variable. If you
put 'from __future__ import nested_scopes' at the top of the file it
would work as expected (or use version 2.2 as nested scopes are
mandatory then).
| Here is a version that works without warnings.
|
| def mtrx(l):
| '''Returns a function which will accessess l[i][j] as l(i,j).
| '''
| def a(i,j,m=l):
| return m[i][j]
| return a
|
| l=[[1,2],[3,4]]
| a=mtrx(l)
| print a(1,1)
|
| # results in
| # 4
In this version you used a different name in the inner vs. outer
functions (hence no warnings) and explicitly created a variable that
is local to 'a' which is why it works.
-D