Movatterモバイル変換
[0]ホーム
Confused about nested scoping
Bjorn PettersenBPettersen at NAREX.com
Wed Apr 18 19:33:01 EDT 2001
They're nested lexical scopes, not dynamic scopes (which is what you wereexpecting).An example of a nested lexical scope would be e.g.:1 def outer():2 spam = 'bacon'3 def printspam():4 print spam5 printspam()1: Defines an outer function2: creates a variable, spam, that is local to outer3: creates a lexically nested function, printspam4: 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 PMTo:python-list at python.orgSubject: Confused about nested scopingI 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_scopesdef 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 eggsBut I thought with nested scopes I would get spam has value eggs spam has value baconBecause the second printspam's enclosing scope would be that ofscopetest 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-listmailing list
[8]ページ先頭