Newbie: Why Does This Work This Way...Global Variables And The Signal Module....

Markus Schaber markus at
Fri Sep 14 12:05:26 CEST 2001


John Branthoover <jbranthoover at> schrub:

>     I have written a simple program to break out of a endless loop by
> hitting control C,  see below.  This program works OK but I don't
> understand why I have to define the global variable "Loop_Run" twice
> to get it to work. I thought that you had only to define a global
> variable once at the beginning of a program and that made it available
> to rest of the module.

The global statement is no definition in this way. All variables are 
usually from their local scope, so if you do

def f():

then this sets the variable local to the current function. The global 
statement just tells the byte-code compiler to use the global variable 
loop_run during the current function whenever anything accesses 
loop_run. Imagine this as some kind of "search redirection" which says 
"don't use local scope, but global scope for this name".

So you have to tell this in every function and method you need it.

Also remember that the variable is created on the first write access to 
it. A "definition" - as known from static languages - is not knowt to 

Another point is that the python interpreter allows omitting the global 
statement whenever the variable is only read and not written in the 
function - because in this case, there can't be a local variable.

So you could rewrite your example as follows:

import signal

def signal_handler(signal, frame):
    global Loop_Run
    print 'Signal Handler',Loop_Run

def Main():
    while Loop_Run<>0:
        print 'Loop is running because Loop_Run = ',Loop_Run
    print  'Loop is stopped because Loop_Run = ',Loop_Run

signal.signal(signal.SIGINT, signal_handler)

if __name__=='__main__':

"The strength of the Constitution lies entirely in the determination of 
each citizen to defend it. Only if every single citizen feels duty 
bound to do his share in this defense are the constitutional rights 
secure." -- Albert Einstein

More information about the Python-list mailing list