[Tutor] Funtions, modules & global variables

Dave Angel d at davea.name
Mon Sep 26 01:58:07 CEST 2011

On 09/25/2011 07:21 PM, 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.
> 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.
> 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*
> Below is a some of the script for both folder, just note that their will be
> many functions in each folder
> Any help will be greatly appreciated!!!
> #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
>                      TSFC=ncfile.variables['T_SFC'][:,:,:]
>                      LAT=ncfile.variables['latitude'][:]
>                      LON=ncfile.variables['longitude'][:]
>                      TIME=ncfile.variables['time'][:]
>                      fillvalue=ncfile.variables['T_SFC']._FillValue
>                      ncfile.close()
> #plotdata.py
> from selectdata import selectalldata
> selectalldata()
> def plotncfilewithtime():
>      for TSFC, TIME in zip((TSFC[1::3]),(TIME[1::3])):
>      #convert time from numbers to date and prepare it to have no symbols for
> saving to filename
>          cdftime=utime('seconds since 1970-01-01 00:00:00')
>          ncfiletime=cdftime.num2date(TIME)
>          print ncfiletime
>          timestr=str(ncfiletime)
>          d = datetime.strptime(timestr, '%Y-%m-%d %H:%M:%S')
>          date_string = d.strftime('%Y%m%d_%H%M')
>          map = Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33,
> llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i')
>         x,y=map(*N.meshgrid(LON,LAT))
>          map.drawcoastlines(linewidth=0.5)
>          map.readshapefile(shapefile1, 'DSE_REGIONS')
>          map.drawstates()
>          plt.title('Surface temperature at %s UTC'%ncfiletime)
>          ticks=[-5,0,5,10,15,20,25,30,35,40,45,50]
>          CS = map.contourf(x,y,TSFC, ticks, cmap=plt.cm.jet)
>          l,b,w,h =0.1,0.1,0.8,0.8
>          cax = plt.axes([l+w+0.025, b, 0.025, h], )
>          cbar=plt.colorbar(CS, cax=cax, drawedges=True)
>          plt.savefig((os.path.join(outputfolder,
> 'TSFC'+date_string+'UTC.png')))
>          plt.close() # must use plt.close() so that colorbar works!
>      print "end of processing"
> plotncfilewithtime()
1) If you're just learning how to split a long top-level script into 
functions, don't confuse the issues by also trying multiple source 
files, and especially multiple folders of source files.  Learn one 
concept before starting on the other.

2) when you mention an error message, give the whole thing, including 
stack trace.  or one thing, that'd mean we could see which line actually 
got the error.

3) if a function doesn't take any arguments and doesn't return any 
values, you're probably wasting your time.  Separate functions that only 
share by global variables aren't much better than top-level code.

4) When you declare a global in a function, please do it at the 
beginning of the function, right after the docstring.

5) Use all caps for constants, not for ordinary varables.  It's just a 
convention, but it'll make the code easier for others to read.

6) That particular error means that a variable in a function, WITHOUT a 
global statement, has been used as an rvalue, without first having been 
given a value.   The most common cause for that is that the assignment 
occurs inside a conditional, but you get the error when that particular 
branch doesn't happen.

Since your present code is in multiple files, I'll also point out:   
global means global to the one module, not global to the whole program.



More information about the Tutor mailing list