Question about scope

Donn Cave donn at u.washington.edu
Thu Jul 5 18:31:44 EDT 2001


Quoth Carsten Gaebler <clpy at snakefarm.org>:
| Tim Daneliuk wrote:
|> I guess what I want to know is when globally declared objects are seen inside a function, class, or
|> block, and when they must be explicitly declared as being global.
|
| You can always 'read' a global variable in a function, e.g.
|
| g = 0
| def func():
|   print g
| func()
|
| prints '0'. If you want to modify a global variable inside a function you
| need to declare it as global:
|
| g = 0
| def func():
|   global g
|   g = 1
| func()
| print g
|
| prints '1'.
|
| Otherwise an assignment inside a function will create a new variable in
| the local namespace:
|
| g = 0
| def func():
|   g = 1
| print g
|
| prints '0' because g=1 only exists inside func().

As long as we're here - the queerest thing is when you combine the
two in this order:

g = 0
def func():
  print g
  g = 1

That will raise an "UnboundLocalError", because (as I understand it)
the interpreter already classified g as local at "compile" time, when
it saw the assignment.  Not at run time when it actually performs the
assignment.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list