global vars?

Gordon McMillan gmcm at hypernet.com
Thu Jun 10 09:54:22 EDT 1999


Holger Jannsen writes:

> Why do I have to declare that variable again as global in that
> class-procedre (with :	global PREDEFINED_PROGDIR)?
> If I don't do that the value of that variable outside of that 
> procedure is the old one.
> It seems that python takes a global variable inside a procedure in a
> class but not outside.

Without some code to demonstrate your confusion, it's difficult to 
guess exactly why you're feeling confused.

In both cases, changing the binding of a global variable requires a
"global" statement within the function / method. Without that 
statement, Python takes an assignment to the variable (a binding) to 
be local in scope (that is, it's a new variable that exists only 
within the function / method).

This does not apply to reading a variable - Python will search first 
the locals, then the globals. So you can modify a mutable variable 
(eg, append a string to a global list of strings) without a "global" 
statement. The binding of the global variable (the name -> object 
binding) is not changed, so the rule doesn't apply.

So in your case, the different behaviors are due to something else 
you're doing, not to the fact that one is in a function and the other 
in a method.

- Gordon




More information about the Python-list mailing list