473,394 Members | 1,703 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

The global statement

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
8 102731
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
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
"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
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
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
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
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
"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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Andr? Roberge | last post by:
I have the following two files: #--testexec.py-- def exec_code(co): try: exec co except: print "error" #-- test.py--
10
by: Ranga | last post by:
I was unable to run the statement "CREATE GLOBAL TEMPORARY TABLE" on unix version of DB2, it gave the follwing error db2 => create global temporary table temp ( OGI_SYS_NR char(8) ) DB21034E ...
4
by: NoNickname | last post by:
Hi, I need to get a string from a COM component at application start. (It's a Long Story and I cannot change this fact.) In ASP.NET 1.1, I simply called this COM component in Global.asax.cs...
16
by: didier.doussaud | last post by:
I have a stange side effect in my project : in my project I need to write "gobal" to use global symbol : .... import math .... def f() : global math # necessary ?????? else next line...
0
by: jochen.stier | last post by:
Hi everyone, I am compiling the following script using Py_CompileString def compute(node): #global compute iter = node.getChild(0)
9
by: Ed Jensen | last post by:
I'm having a vexing problem with global variables in Python. Please consider the following Python code: #! /usr/bin/env python def tiny(): bar = for tmp in foo: bar.append(tmp) foo = bar
5
by: TheFlyingDutchman | last post by:
Does anyone know how the variables label and scale are recognized without a global statement or parameter, in the function resize() in this code: #!/usr/bin/env python from Tkinter import...
3
by: oyster | last post by:
why the following 2 prg give different results? a.py is ok, but b.py is 'undefiend a' I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) on win32 #a.py def run(): if 1==2: ...
20
by: teddysnips | last post by:
Weird. I have taken over responsibility for a legacy application, Access 2k3, split FE/BE. The client has reported a problem and I'm investigating. I didn't write the application. The...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.