Lexical Scope

M

Matt Knepley

I must be misunderstanding how Python 2.3 handles lexical scoping.
Here is a sample piece of code:

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

which gives the output:

1
1

whereas this piece of code:

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

gives:

2
1

and finally this code bombs:

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

with an error about UnboundLocal. 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?

Matt
 
G

Gary Herron

I must be misunderstanding how Python 2.3 handles lexical scoping.
Here is a sample piece of code:

The rule is this simple:

An assignment to a variable *ANYWHERE* within a block of code makes
that variable local *EVERYWHERE* within that block, possibly hiding
variables of the same name in outer scopes.

That rule will explain all three of your examples.

Gary Herron
 
W

Werner Schiendl

Hi,

Matt said:
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:
.... a = [1]
.... def run2(b):
.... print a[0]
.... a[0] = b
.... run2(2)
.... print a[0]
.... 1
2

Or you can use a global variable like so:
.... global a
.... a = 1
.... def run2(b):
.... global a
.... print a
.... a = b
.... run2(2)
.... print a
.... 1
2


It depends on what you are trying to accomplish :)


hth

Werner
 
P

Paul Clinch

From the language lawyers section of python doc.s :-

"If a name is assigned to anywhere in a code block (even in
unreachable code), and is not mentioned in a global statement in that
code block, then it refers to a local name throughout that code
block."

Try:-

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top