Confused about nested scoping
Bjorn Pettersen
BPettersen at NAREX.com
Wed Apr 18 19:33:01 EDT 2001
They're nested lexical scopes, not dynamic scopes (which is what you were
expecting).
An example of a nested lexical scope would be e.g.:
1 def outer():
2 spam = 'bacon'
3 def printspam():
4 print spam
5 printspam()
1: Defines an outer function
2: creates a variable, spam, that is local to outer
3: creates a lexically nested function, printspam
4: If you do from __future__ import nested_scopes,
this line prints the contents of the variable spam
set in the lexically enclosing scope on line 2.
In traditional Python this would raise a NameError
since spam isn't in the local or the global
namespace.
hth,
-- bjorn
-----Original Message-----
From: Stephen R. Figgins [mailto:fig at monitor.net]
Sent: Wednesday, April 18, 2001 5:18 PM
To: python-list at python.org
Subject: Confused about nested scoping
I seem to be misunderstanding what nested scopes do.
>From AMK's summary of 2.1 changes:
Put simply, when a given variable name is not assigned a value
within a function (by an assignment, or the def, class, or import
statements), references to the variable will be looked up in the
local namespace of the enclosing scope.
Here is what I tried:
from __future__ import nested_scopes
def printspam():
print "spam has value %s" % (spam)
def scopetest():
spam = 'bacon'
printspam()
spam = 'eggs'
printspam()
scopetest()
I figured without nested scopes I would get
spam has value eggs
spam has value eggs
But I thought with nested scopes I would get
spam has value eggs
spam has value bacon
Because the second printspam's enclosing scope would be that of
scopetest in which I had reassigned spam.
But I still get eggs with my spam.
What am I misunderstanding?
-Stephen
--
http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list