Lexical Scope

From: Matt Knepley (knepley_at_mcs.anl.gov)
Date: 10/30/03


Date: 30 Oct 2003 07:59:04 -0800

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



Relevant Pages

  • Problem with Lexical Scope
    ... I am not completely knowledgable about the status of lexical scoping in ... Python, but it was my understanding that this was added in a long time ... def collect: ...
    (comp.lang.python)
  • Re: Why no lexical scoping for a method within a class?
    ... def a: ... Lexical scoping is going on here, you're just mistaking what's being scoped; it's the |self| in |b|, which is in scope because it's a parameter. ... then Python would whinge mightily at you, claiming that it knoweth naught of this |x| attribute of which you speak, and can it go home now for this is a silly place. ... The |self| in |b| is still in lexical scope, ...
    (comp.lang.python)
  • Re: Lexical Scope
    ... On Thursday 30 October 2003 07:59 am, Matt Knepley wrote: ... > I must be misunderstanding how Python 2.3 handles lexical scoping. ... variables of the same name in outer scopes. ... > def run2: ...
    (comp.lang.python)
  • Why no lexical scoping for a method within a class?
    ... sloppy, and inconsistant. ... Or is there some good reason for this? ... def a: ... i.b# this works, why no lexical scoping? ...
    (comp.lang.python)
  • text adventure question
    ... I am working on a text adventure game for python to get back into ... def character_sheet: ... global reputation ... print "Please choose another command. ...
    (comp.lang.python)