[Tutor] Assessing local variable outside function

Alan Gauld alan.gauld at yahoo.co.uk
Fri Oct 28 04:20:28 EDT 2016


On 28/10/16 02:38, nils wagenaar wrote:
> Hello,
> 
> 
> Could i use a variable defined in a function in another function?

By returning it to the caller.

> def DatasetToSubset(file, LatUpbound, LatLowBound, LonUpBound, LonLowBound):
>      nc=netCDF4.Dataset(file)
>      lats=nc.variables['lat'][:]; lons=nc.variables['lon'][:]
>      latselect=np.logical_and(lats > LatLowBound, lats < LatUpBound)
>      lonselect=np.logical_and(lon > LonLowBound, lon < LonUpBound)
>      data=nc.variables['Runoff'][1000, latselect, lonselect]
>      return data; return latselect; return lonselect

The syntax for return is

return value

And you can only have one return on the line.

But value can be a tuple so to do what you want:

     return data, latselect, lonselect

And your caller can use something like


dat,lat,lon = DatasetToSubset(....)

The other way to do it is to create a class containing
all the functions that use the same data and put the
shared variables as instance attributes.

class LatAndLon:    # think of a better name! :-)
   def __init__(self, file, lat=None, lon=None):
      self.file = file
      self.lat = lat
      self.lon = lon

   def datasetToSubset(self, .....):
     nc = ...
     ...
     self.lat = ...
     self.lon = ...
     self.data = ...

   def another_function(self,...):
     if self.lat == 42:
        self.process(data)
     elis self.lon > 66:
        self.format()
     #etc...

Then create an instance and call the methods as needed

vals = LatAndLon(....)
vals.datasetToSubset(....)
vals.another_function(....)

That way the data stays outside the global namespace
but the functions that use it can all see it.
You will likely find that this greatly reduces the
number of params you need to pass to each function
since you set them up once, when you create the
instance, and don't need to keep passing them
into the functions. This makes the code easier
to write and maintain.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list