[Tutor] Global scope

alan.gauld@bt.com alan.gauld@bt.com
Mon Feb 3 12:20:10 2003


> I am confused about global variables.  I have a C/C++ program 
> with a large number of functions, and a block of global variables 

> ...that I'm converting to python.  I am translating the 
> functions into corresponding modules. 

If you don't store them in separate files in C++ why do so in 
Python (or maybe that should be the other way around?!)

> functions, etc.  How do I declare some variables, including lists and
> dictionaries, that are used in these lower functions to be globals,
> accessible by all functions?

Put the variables in a module and import that module into the 
other modules that need access to them.

Much better to reduce the globals thgough either by passing 
them as parameters to the functions or, better still, bundling
them up as a class and making your functions methods of the class.

If these functions are all related to the same set of global 
data theres a good chance they are functionally related too. 
If so they would be a good class candidate.

> I used a statement such as:  global case_number in a 
> function, and declare it case_number = 0 in the main 
> module, but I get:

global in python means the variable is in the same file
but not in the same function. You need to import your main 
module then referebce the globals there:

import main

def myfunc():
    main.foo = 42
    return 5 * main.x

etc...

Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/