Mailing List Archive

global vars?
Hi there,

I'm a newbie at python and there's something I don't understand:

I'd like to have some global variables e.g. PREDEFINED_PROGDIR.
It should have a predefined value e.g. "C:\\programs" in an
init-procedure. Then, there's a loop in another procedure,
which reinitializes that variable every time calling that
init-procedure.
Also the loop creates every time a new instance of an class where
is another procedure that could give another value to that variable
e.g. "C:\\programs\\myprogram", so I want to work with that
new value further until a new item of the loop occurs.
[Check it?]

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.

What's about my "narf" in my brain?

Ciao,
Holger
global vars? [ In reply to ]
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
global vars? [ In reply to ]
Hi,


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

Sorry, but I think, you already answered my question.

> 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
^^^^^^^^^^^^^ ^^^^^^
That's it.

>...
>
> - Gordon

Thanx,
Holger