There is a simple class where I want to store some functions statically in a dictionary using different ways:
import os, sys
class ClassTest():
testFunc = {}
def registerClassFunc(self,funcName):
ClassTest.testFunc[funcName] = eval(funcName)
@classmethod
def registerClassFuncOnClass(cls,funcName):
cls.testFunc[funcName] = eval(funcName)
@staticmethod
def registerClassFuncFromStatic(funcName):
ClassTest.testFunc[funcName] = eval(funcName)
Some example methods:
def user_func():
print("I run therefore I am self-consistent")
def user_func2():
print("I am read therefore I am interpreted")
def user_func3():
print("I am registered through a meta function therefore I am not recognized")
def user_func4():
print("I am registered through an instance function therefore I am not recognized")
def user_func5():
print("I am registered through a static function therefore I am not recognized")
And a little test:
if __name__ == "__main__":
a = ClassTest()
a.testFunc["user_func"] = user_func
a.testFunc["user_func"]()
a.testFunc["user_func2"] = eval("user_func2")
a.testFunc["user_func2"]()
ClassTest.testFunc["user_func"] = user_func
ClassTest.testFunc["user_func"]()
ClassTest.testFunc["user_func2"] = eval("user_func2")
ClassTest.testFunc["user_func2"]()
a.registerClassFunc("user_func5") # does not work on import
a.testFunc["user_func5"]()
ClassTest.registerClassFuncFromStatic("user_func3") # does not work on import
ClassTest.testFunc["user_func3"]()
ClassTest.registerClassFuncOnClass("user_func4") # does not work on import
ClassTest.testFunc["user_func4"]()
All this works provided all these elements are in the same file. As soon as the functionality is split up in 2 files and a main file:
from ClassTest import ClassTest
from UserFunctions import user_func,user_func2, user_func3, user_func4, user_func5
if __name__ == "__main__":
a = ClassTest()
a.testFunc["user_func"] = user_func
...
Only the first two keep working (setting the function directly), the others - using a function to do the same thing - give a NameError
on all the eval
calls. For instance: NameError: name 'user_func5' is not defined
.
What is the logic here for the loss of scope when using the methods versus directly setting the functions? And can I get it to work using imports from other packages so I can place any function in the class with a method rather than directly?