Guilty secret: globals baffle me
Dennis Lee Bieber
wlfraed at ix.netcom.com
Wed Nov 6 18:38:12 EST 2002
Edward K. Ream fed this fish to the penguins on Wednesday 06 November
2002 06:43 am:
> My questions:
>
> 1. How many globals are there? Is there just one, or does each module
> define its own?
>
In a simplistic sense, globals are names which exist at the top level
of each module (or .py file, including your "main" program). Locals are
names which are created/used inside of nested definition levels...
aGlobal = []
def something(arg):
aLocal = arg
class someitem(): #warning, very loose usage here, likely not runable
aClassLocal = 1
def __init__(self, arg):
aInstanceLocal = arg
> 2. It seems that:
>
> global foo
> foo = x
> ...
> global
> print foo
>
> only works if the two parts are within the same module, so I think
> maybe globals() returns module specific stuff, but then why call it
> globals?
>
The global statement is needed /inside/ def/class components in order
to reference the stuff at the module level.
aGlobal1 = []
aGlobal2 = []
def something(arg1, arg2):
global aGlobal2
aGlobal1 = arg1 #DOES NOT ACCESS aGlobal1! Creates a LOCAL named
aGlobal1
aGlobal2 = arg2 #because of the global statement, this really does
#access the expected global
To get to stuff in an imported module, in a way that the module also
sees it, requires
import module
module.globallevelname ...
Do not use
from module import globallevelname
as that just makes reference to the module's name, and uses the same
name in the importing file. The first time you assign to that name, you
change the reference -- you do not change what was inside the module
itself.
--
> ============================================================== <
> wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
> wulfraed at dm.net | Bestiaria Support Staff <
> ============================================================== <
> Bestiaria Home Page: http://www.beastie.dm.net/ <
> Home Page: http://www.dm.net/~wulfraed/ <
More information about the Python-list
mailing list