[Tutor] Funtions, modules & global variables

Dave Angel d at davea.name
Tue Sep 27 02:52:28 CEST 2011


(Don't top-post.  Put your new remarks after whatever you're quoting)

On 09/26/2011 08:26 PM, questions anon wrote:
> Thanks for your feedback. I might be asking the wrong questions.
> I have written a number of scripts that do various things for each step:
> 1. get data (e.g. Dec-jan-feb, only januarys, all data)
> 2. summary stats(e.g. max, min, frequency)
> 3. plot data (e.g. plot with time, plots subplots, plot with particular
> projection)
>
> I would like to then be able to choose which script for each step and
> somehow feed the data/variables written in earlier functions through to then
> be able to run something like:
>
> def main():
>       getdataDJF()
>       calculatemean()
>       plotmean()
> main()
>
> Is this possible? Is this the correct way to do things?
> My main problem is not being able to feed the output from one function into
> the next.
> Thanks
> Sarah
>
>
If multiple functions need to share data, it should be done by passing 
parameters, and returning results.  If you can understand how to do that 
within a single source file, you'll be ready to extend the concept to 
multiple source files.

But if you just want to skip to a solution, without worrying about 
whether it makes sense, read on.

You have multiple files, how do they relate to each other?  What is the 
kind of data you're trying to share?

I'll make a crazy guess, since you still give no clue.

Perhaps each of your multiple files, called external1.py, external2.py 
defines three functions, called getdataDJF(), calculatemean(), and 
plotmean().  They're defined as follows:

getdataDJF - takes arg1, arg2 and arg3 as parameters, and returns 
results as   (res1, res2)
calculatemean - takes  arg1 and arg2 as parameters, and returns mydata 
as result
plotmean  - takes mydata and device as parameters, and doesn't return 
anything

So your script could do a conditional import to get various 
implementations of the functions.

import sys
if (something):
        from   external1 import getdataDJF, calculateman, plotmean
else:
        from   external2 import getdataDJF, calculateman, plotmean


def main(argv):
       (res1, res2) = getdataDJF(argv[1], argv[2], argv[3])
       buffer = calculatemean(res1, res2)
       plotmean(buffer, argv[4])

main(sys.argv, "printer")

Another approach if this guess is wrong:    use classes.  Keep all the 
data as attributes of a class instance, and the methods can share data 
by stuffing it in those attributes.

-- 

DaveA



More information about the Tutor mailing list