Lexical Scope

Werner Schiendl ws-news at gmx.at
Thu Oct 30 11:38:43 EST 2003


Hi,

Matt Knepley wrote:

> 
> It seems that lexical scope works
> only for references, and as soon as I make an assignment a new local
> is created. Is this true?
> 

Yes (short answer)


If you really need to modify some variable in an outer scope you can
use a mutable object for that kind of thing, like so:

 >>> def run():
... 	a = [1]
... 	def run2(b):
... 		print a[0]
... 		a[0] = b
... 	run2(2)
... 	print a[0]
... 	
 >>> run()
1
2

Or you can use a global variable like so:

 >>> def run():
... 	global a
... 	a = 1
... 	def run2(b):
... 		global a
... 		print a
... 		a = b
... 	run2(2)
... 	print a
... 	
 >>> run()
1
2


It depends on what you are trying to accomplish :-)


hth

Werner





More information about the Python-list mailing list