Problem with global variables

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Mon Apr 2 10:43:38 EDT 2007


Bjoern Schliessmann schreef:
> Laurent Pointal wrote:
> 
>> And so the solution to add "global foo" before using it.
> 
> Didn't you read his final question?
> 
> | All of a sudden, tiny() can see the global variable "foo".  Very
> | confusing!  Why is it that tiny() sometimes can, and sometimes
> | can't, see the global variable "foo"?
> 
> I have no explanation for this, but I'm interested in one, too.

Within functions Python can read from global variables, even without a 
'global' statement. Complications only arise when you try to write to 
it: in that case Python assumes it is a local variable instead of a global.

It surprised me a bit when I first found out about this: I would have 
thought that Python would threat it as a local throughout the function 
until the function assigns something to it. That's not what happens: if 
the function assigns to it, *all* mentions of the variable are 
considered local.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Python-list mailing list