By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
426,083 Members | 1,608 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 426,083 IT Pros & Developers. It's quick & easy.

The global statement

P: n/a
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.
--
David.H
Jul 18 '05 #1
Share this Question
Share on Google+
8 Replies


P: n/a
On Wed, 23 Jul 2003 16:56:08 +0200, Thomas GŁttler wrote:
If foo and bar are in the same file,
you don't need the "global".


Then when is "global" required? What is it's role?

Thanks for your reply.
--
David.H
Jul 18 '05 #2

P: n/a
Thomas GŁttler wrote:

global BAD
BAD=1

def foo():
global BAD
print BAD


Note: the first use of global above, outside a function, is redundant.

-Peter
Jul 18 '05 #3

P: n/a
"David Hitillambeau" <ed****@intnet.mu> wrote in
news:pa****************************@intnet.mu:
On Wed, 23 Jul 2003 16:56:08 +0200, Thomas GŁttler wrote:
If foo and bar are in the same file,
you don't need the "global".


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()

--
Duncan Booth du****@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #4

P: n/a
Thomas GŁttler fed this fish to the penguins on Wednesday 23 July 2003
07:56 am:
David Hitillambeau wrote:
read and write access over it.
If foo and bar are in the same file,
you don't need the "global".

He does for the "write access"...

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Bestiaria Home Page: http://www.beastie.dm.net/ <
Home Page: http://www.dm.net/~wulfraed/ <


Jul 18 '05 #5

P: n/a
On Wed, 23 Jul 2003 16:56:08 +0200, Thomas =?ISO-8859-15?Q?G=FCttler?= <gu******@thomas-guettler.de> wrote:
David Hitillambeau wrote:
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.
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 = 'global BAD'
def baz(): ... BAD = 'local assignment binds locally unless global is specified'
... print BAD
... baz() local assignment binds locally unless global is specified print BAD global BAD
def baz(): ... global BAD
... BAD = 'assigned locally, but destination global instead because of "global BAD"'
... print BAD
... print BAD global BAD baz() assigned locally, but destination global instead because of "global BAD" print BAD assigned locally, but destination global instead because of "global BAD"
BAD = 'global BAD'
def baz(BAD=BAD): ... BAD += ' -- local mod to local arg pre-bound to global BAD when baz defined'
... print BAD
... print BAD global BAD BAD = 'changed global'
print BAD changed global baz() global BAD -- local mod to local arg pre-bound to global BAD when baz defined print BAD

changed global

HTH

Regards,
Bengt Richter
Jul 18 '05 #6

P: n/a
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 variableat
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

Jul 18 '05 #7

P: n/a
Andy Jewell <an**@wild-flower.co.uk> wrote in
news:ma**********************************@python.o rg:
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.

--
Duncan Booth du****@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #8

P: n/a
"David Hitillambeau" <ed****@intnet.mu> writes:
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()
-----------------------------

HTH,

Nick

--
# sigmask || 0.2 || 20030107 || public domain || feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?')
Jul 18 '05 #9

This discussion thread is closed

Replies have been disabled for this discussion.