0

I have a few lines that add results from functions to a list. I'm trying to turn it into a loop rather then continuous lines of assignments and append's.

so far i have the code how I want it, I'm just struggling to turn the actual string into calls to functions. I've read the pocket python guide and various other python books yet am unable to find the solution.

    categories = ['Hours', 'Travel', 'Site', 'Date']
    indexloc == 0
    for i in categories:  
        func = 'v'+categories[indexloc]+' = Get'+categories[indexloc]
        indexloc += 1

The results that i get are spot on im just unsure how to translate them into function calls:

>>> 
vHours = GetHours
vTravel = GetTravel
vSite = GetSite
vDate = GetDate
>>>

(Just to clarify the Get parts are the function calls)

I've read Calling a function of a module from a string with the function's name in Python but im failing to see if/how it applies to my situation

Python 2.7 razcrasp@gmail.com Thanks

Community
  • 1
  • 1
SidSpace
  • 27
  • 5
  • Where/how are your functions that you want to called are defined? – metatoaster Aug 25 '14 at 02:56
  • They are defined previously in the code. They all work fine as they are and require no parameters. The Functions are the 4 in the results piece. GetHours, GetTravel, GetSite & GetDate. I need to convert them from strings to function calls – SidSpace Aug 25 '14 at 03:03

1 Answers1

2

To call a function, you need to have some reference to it. Since you know the name of the function, you can get it from the local variables:

for category in categories:
    function = locals()['Get' + category]

    print 'v{} = {}'.format(category, function())

A better way to do this would be to map your category names to functions:

category_mapping = {
    'hours': GetHours,  # CamelCase is usually for classes, not functions
    'travel': GetTravel,
    ...
}

for category, function in category_mapping.items():
    print 'v{} = {}'.format(category.capitalize(), function())
Blender
  • 289,723
  • 53
  • 439
  • 496