The global statement

D

David Hitillambeau

Hi guys,
As I am new to Python, i was wondering how to declare and use global
variables. Suppose i have the following structure in the same module (same
file):

def foo:
<instructions>
<instructions>
def bar:
<instructions>
<instructions>

I want to enable some sharing between the two functions (foo and bar)
using one global variable in such a way that each function can have read
and write access over it.

How can i manage this please?

I've read about "The global statement" in python's documentation and still
can't figure out it's use.

Thanks.
 
D

Duncan Booth

Then when is "global" required? What is it's role?
I'm afraid Thomas Güttler's answer was a bit misleading.

You never need to use the 'global' statement outside a function. The only
effect of 'global' is to declare that a variable assigned to within a
function is actually a global variable. The fact that it is a global
variable lasts only for the duration of the function in which it occurs.

Global variables are not in fact global. They are global only to the module
in which they occur (usually you get one module per source file, although
be aware that if you run a script A.py, it runs in the module __main__ and
importing A will give you a second module from the same source, with its
own global variables).

If you want to access a global variable from another module you don't need
a global statement, just prefix the variable with a reference to the
module. e.g. 'A.x' will access the global 'x' in module 'A'.

So:

BAD=1

def foo():
global BAD
BAD = 2

def bar():
BAD = 3
global BAD

def xyzzy():
BAD="xyzzy"

def plugh():
print "BAD is",BAD

Outside the function assigning to BAD makes it a global variable. Inside
foo and bar the global statement makes BAD a global variable for the
assignment, notice that it doesn't matter where in the function the global
statement occurs, although it is conventional to list globals at the head
of the function.

'xyzzy' simply sets a local variable with the same name as the global.

'plugh' accesses the global: if you don't try to assign to it you don't
need to tell Python its a global.

Finally, all of this confusion can be avoided if you use classes instead of
global variables. e.g.

class MyClass:
def __init__(self):
self.value = 0

def foo(self):
self.value = 1

def bar(self):
self.value = 2

obj = MyClass()
obj.foo()
obj.bar()
 
D

Dennis Lee Bieber

Thomas Güttler fed this fish to the penguins on Wednesday 23 July 2003
07:56 am:
If foo and bar are in the same file,
you don't need the "global".
He does for the "write access"...

--
 
B

Bengt Richter

Hi David,

global BAD
Don't need the above line if you are already in global scope.
BAD=1

def foo():
global BAD
print BAD

def bar():
global BAD
print BAD

foo()
bar()

If foo and bar are in the same file,
you don't need the "global".
Unless you want to rebind it. Then you need it in order not
to get the default behaviour of creating a local within the function.
E.g., here are some variations to think about. Note what gets changed and when:
... BAD = 'local assignment binds locally unless global is specified'
... print BAD
... global BAD


... global BAD
... BAD = 'assigned locally, but destination global instead because of "global BAD"'
... print BAD
... assigned locally, but destination global instead because of "global BAD"


... BAD += ' -- local mod to local arg pre-bound to global BAD when baz defined'
... print BAD
... changed global

HTH

Regards,
Bengt Richter
 
A

Andy Jewell

Gentlepeople,

I found it easier to envisage the Python global statement as the inverse of
the Pascal/Modula/C concept:

In traditional (compiled procedural) languages, one *declares* a variable at
the 'top-level' scope, and then uses it as one would a local variable in
functions/procedures, but without declaring it again. Global variables in
these types of languages are treated differently in most respects (where they
are stored for example: heap rather than stack, usually). There is usually
no special notation, however, to enable the reader (especially one not
skilled in the language at hand) to determine that a given variable is, in
fact, global or local: you have to know the scoping rules of the language.
If you define a variable outside of a function, it's global (notwithstanding
the placement/sequencing rules for that language).

Python is different (as always). It allows you to *read* the value (pardon
the over-simplification) of variables declared at the 'top level', that is,
created outside of a function, but you can't *write* to it without first
telling Python that you wish to do so (by using the global statement):
forgetting to do so results in the creation of a similarly named local
variable, with no relation whatsoever to the intended global variable. I tend
to think of it as 'telling python it's ok to change' the variable.


pascal;

var a_global: integer;

function read_a_global;
begin
read_a_global:=a_global; (* return the value of global variable *)
end;

procedure modify_a_global;
begin
a_global:=10; (* modify global variable *)
end;

end.


#python:
a_global=1

def read_a_global():
return a_global # REFERENCE the global variable

def cant_modify_a_global():
a_global = 10 # makes a local variable called a_global
# which disappears after this point:

def modify_a_global(n):
global a_global # Makes a_global locally accessible for modifying
a_global = 10 # top-level a_global variable is modified



When I first tried to do this sort of thing in python, i wrote:

global a_global

def modify_a_global():
a_global=10

...and wondered why it didn't work. I admit that the docs didn't really help
much either, as they don't tell you to put the statement *inside* the
function that needs to modify the variable! I only finally understood by
reading some of the standard library code, after searching it for the word
'global' itself!

just my 2p...

hope that helps

-andyj
 
D

Duncan Booth

I found it easier to envisage the Python global statement as the
inverse of the Pascal/Modula/C concept:

Indeed, Pascal/Modula/C say "here's a variable, use it anywhere! Program
structure? Who needs it?". Python, OTOH, requires you to say near the point
of use "I am going to break the rules of good program design, but just for
this function."

In some ways this is analagous to the COMEFROM statement (see
http://www.fortran.com/fortran/come_from.html). Just not very.
 
N

Nick Vargish

David Hitillambeau said:
I want to enable some sharing between the two functions (foo and bar)
using one global variable in such a way that each function can have read
and write access over it.

Using the "global" statement seems unpythonic to me, for reasons I'm
too lazy to come up with good ways to express. :^) This is what I do,
if I need something like this:

-----------------------------
class Global:
"""Generic container for shared variables."""
pass

def foo():
Global.somevar = 'set in foo'

def bar():
print Global.somevar

foo()
bar()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top