using 'global' across source files.

D-Man dsh8290 at rit.edu
Wed Jan 3 07:58:41 EST 2001


On Wed, Jan 03, 2001 at 10:17:32AM +0100, Bram Stolk wrote:
> I thought that python's 'global' acted like C's 'extern' cmd,
> meaning, that 'global val' does NOT define/create 'val',
> only refers to a val that exists somewhere else.
> 

'global' is not the same as 'extern'.  In python there are only 2
scopes (actually 3): local (inside a function), module, and builtin.
If you are inside a function and you try to do an assignment, you will
assign to a local variable.  If it doesn't exist yet you have just
created it.  If this isn't what you want, you tell the interpreter
with the 'global' keyword.  It then searches for the variable in an
outer scope (the module) rather than creating a new local variable.

'global' doesn't actually *do* anything except inform the interpreter
of your intent.  The variable was created when you executed the
assignemnt, not global.


In C, however, you must explicitly declare variables first.  This is
how a C compiler knows where to assign the value to.  Since C's static
type checking, etc, must know where to find a variable and check that
it's name/type match the operation you need to tell it that there is
such a variable in existence, but external to the current location.


If you *really* need global variables, I would recommend making a
module such as "Constants" or some other appropriate name and putting
them in there.  Also *don't* use "from <name> import *".  This will
make the names be in the current module's namespace rather than
sharing them with other clients of the imported module.

Maybe it would be better if you redesigned your app to not use global
variables, or to use OO principles instead?

HTH,
-D




More information about the Python-list mailing list