global variables

Chris Barker chrishbarker at home.net
Fri Oct 19 20:11:53 CEST 2001


´ÐÜøÐÝ ³. wrote:
> > I´m experiencing a little problem due to my
> > poor understanding of the way python handles
> > global variables. Basically the problem is the following
> > I have a programm with several variables which
> > I would like to access globaly.
> 
> var=0
> def example_function(??)
>         global var
>         var=var+1
>         (function definition)
> 
> print example_function(10)

You'll get a lot more help here if you post code that is as clse to
functional as possible, so we can see what you mean. Do you want
something like this?

>>> var = 0
>>> def function(n):
...     global var
...     var = var + n
...     return var
...
>>>
>>> function(3)
3
>>> function(3)
6
>>>
>>> function(3)
9
>>> function(3)
12
>>> print var
12

As you can see, the same var is used in all function calls, and the main
namespace. Keep in mind, however, that in Python, "global" means global
to a module, not the the whole program. This is a good thing, because
you wouldn't want a module you import, that you didn't write, to mess
with your global variables.

If you have some data that you want visible to all parts of your
program, you can put them all in a module (call it global_vars.py or
something), and then you can do a:

import global_vars

and access the variables with:

global_vars.var1
global_vars.var2

etc.

You could also put them in a class it you want.

Hope this helps, if it doesn't you need to be more clear about waht you
want to do.

-Chris


-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list