[Tutor] Funtions, modules & global variables
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!!!
> def selectalldata():
> for (path, dirs, files) in os.walk(MainFolder):
> for dir in dirs:
> print dir
> for ncfile in files:
> if ncfile[-3:]=='.nc':
> print "dealing with ncfiles:", path+ncfile
> ncfile=Dataset(ncfile, 'r+', 'NETCDF4')
> global TSFC
> from selectdata import 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')
> print 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,
> map.readshapefile(shapefile1, 'DSE_REGIONS')
> plt.title('Surface temperature at %s UTC'%ncfiletime)
> 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.close() # must use plt.close() so that colorbar works!
> print "end of processing"
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