hi everyone,

I have searched for and answer to this and cannot find any solution. So please forgive me if it is a straight forward answer!

I have a module that is imported. It has a number of subroutines inside it that need to be run, one for each year.

I want to be able to run a loop that runs each sub eg

[ YearbyYear.changes_ + str(year) + season + "_" + forecast + '(' + study + ')']
where the sub names are changes_2009summer_dev(study), changes_2009winter_dev(study), changes_2010summer_dev(study) etc etc
So year, season, and forecast are variables.

Can this be done ??? A loop is so much more elegant than 60 odd lines of if else codes.

Thanks for any help you can give.

This is python; of course it's possible! Here's how to retrieve a function (and call it) from a module object.

# This example imports the 'os' module, tries to retrieve the function 'getcwd' and then calls it.
import os

func = getattr(os, 'getcwd', False) #Tries to get the attribute 'getcwd' from the os module, returns False if it isn't found. Note that the getattr function can retrieve any kind of attribute from any kind of object (well, almost), given a name.

if func:
    func() #Outputs 'C:\\Python30'

Thankyou very much!

That was definately not something I would have found myself!

This question has already been answered. Start a new discussion instead.