[Tutor] Funtions, modules & global variables

Alan Gauld alan.gauld at btinternet.com
Mon Sep 26 02:35:43 CEST 2011

On 26/09/11 00:21, questions anon wrote:
> Hi All,
> I am trying to move from writing one long script each time I need to do
> a new thing but I do not quite understand how functions work, even after
> reading many manuals.

Can you be more specific about what you dpn;t understand.

For example can you understand how this function works?

def square(x):
     return x*x

If not what is the area of difficulty?

> My first attempt is to create a python file where I have defined a
> number of functions that get data in various ways.
> I have also made another python file where I want to plot the data in
> different ways. but I am having trouble getting that data to run in my
> python plotting file.

It may be easier to keep all the functions in a single file initially. 
It just eliminates an extra layer of complexity until we get things 
working. Once you know your functions work we can think about moving 
them into separate files.

> I have made the variable I require 'global' but that doesn't seem to be
> working. I keep receiving:
> /
> UnboundLocalError: local variable 'TSFC' referenced before assignment/

global in Python means global within the current file. It does not mean 
across all files.

> Below is a some of the script for both folder, just note that their will
> be many functions in each folder

I'm not sure I understand that bit. So I'll just ignore it for now! :-)

> #selectdata.py
> def selectalldata():
>          for (path, dirs, files) in os.walk(MainFolder):
>              for dir in dirs:
>                  print dir
>              path=path+'/'
>              for ncfile in files:
>                  if ncfile[-3:]=='.nc':
>                      print "dealing with ncfiles:", path+ncfile
>                      ncfile=os.path.join(path,ncfile)
>                      ncfile=Dataset(ncfile, 'r+', 'NETCDF4')
>                      global TSFC

Normally globals are defined at the top of the function. Its not 
necessary but its where most readers will look for it. In this case 
there is no existing global variable TSFC so it gets created in your 
module space on the assignment.

 >                      TSFC=ncfile.variables['T_SFC'][:,:,:]

I'm not familiar with the [:,:,:] style? What does it do?
Are you sure you want the commas?

But since that happens inside an if block, if the block doesn't get 
executed the global variable will never get created. Any attempt to 
access the variable before the if block is executed will result in your 

>                      LAT=ncfile.variables['latitude'][:]
>                      LON=ncfile.variables['longitude'][:]
>                      TIME=ncfile.variables['time'][:]
>                      fillvalue=ncfile.variables['T_SFC']._FillValue
>                      ncfile.close()

And since there are no other functions in this file nobody else can see 
the TSFC variable you created. And since the function does not return 
any data it will be hard for other modules to use this function.

> #plotdata.py
> from selectdata import selectalldata
> selectalldata()

This will (msometimes) create a TSFC variable in the selectdata module, 
but you will not be able to access it here because you have not imported 
selectdata. If you had you could have done

TSFC = selectdata.TSFC

But since you didn't I suspect that

> def plotncfilewithtime():
>      for TSFC, TIME in zip((TSFC[1::3]),(TIME[1::3])):

This will fail when it tries to slice TSFC which it can't see.
Even if it did work it would be bad practice to do this sin e from the 
next line onwards the original TSFC would be masked by the new TSFC 
variable you are creating. Better to use unique names for the two values.

>      #convert time from numbers to date and prepare it to have no
> symbols for saving to filename
I ignored the techie stuff :-)

>      print "end of processing"
> plotncfilewithtime()

Again, this is not the best way to use functions, better to get the 
function to return the output to be displayed by the other program.


Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list