Sample code file:
MyCode.py
def DoSomething(data):
# data is a string
# find a function in the same scope as this one that has the name contained
# in "data"
try:
func = getattr(self,data) # this is wrong
except AttributeError:
print "Couldn't find function %s." % data
return
# execute the function
func()
def AFunction():
print "You found a function!"
def Add():
print "1 + 1 = %d." % ( (1+1) )
def test():
# unit test
DoSomething("AFunction")
--------
test.py
import MyCode
# Try executing some functions
MyCode.DoSomething("AFunction") # should print You found a function!
MyCode.DoSomething("Add") # should print 1+1=2.
MyCode.DoSomething("IDoNotExist") # should run the exception handler
# Try executing a function from inside the module
MyCode.test() # should print You found a function!
If I were dealing with a class object, that getattr statement would end up retrieving a reference to the function within the class that matches the name provided. Then, as shown, I could execute that function directly from its variable name.
However, since these functions are NOT in a class, rather they are at the module/file level, using getattr on self won't work since we don't have a self reference into a class instance.
My question is: is it actually necessary to wrap this function along with all its supporting functions in a class and instantiate that class just to have this capability? Or, is there an alternative way to use getattr so that I can access the functions defined at the file level.
Notice both use cases: Within the file itself, the "test" function needs to call these functions, but also from outside as imported the function that runs arbitrary other functions might need to run.
Advice appreciated.
Thanks!