Lexical Scope

Gary Herron gherron at islandtraining.com
Thu Oct 30 17:23:01 CET 2003


On Thursday 30 October 2003 07:59 am, Matt Knepley wrote:
> 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



>
> 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









More information about the Python-list mailing list