I try to import a function from a file within a class function. No matter how I turn it around, it results in a NameError when I try to load the function.
The modul code structure is:
def myfunc(params):
return sum(params) # this is just a simple example for demonstration
The class code structure is:
class Pipeline:
def loadfunc(self,filename):
path, modul = arc_filename.rsplit('\\', 1)
modul = modul[:-3] # removing the .py ending
sys.path.insert(1, path)
exec('from ' + modul + ' import *')
### debug prints: ####
if ('myfunc' in dir(modul) and modul.isfunction(modul.myfunc)):
print('myfunc is defined as function in modul ', modul)
if modul in sys.modules:
print(modul, 'was imported successfully')
else:
print(modul, 'was not imported')
try:
myfunc
except NameError:
print("myfunc not in scope!")
else:
print("myfunc in scope!")
I also tried to make the import in the class method in a different way:
class Pipeline:
def loadfunc(self,filename):
path, modul = arc_filename.rsplit('\\', 1)
modul = modul[:-3] # removing the .py ending
os.chdir(path)
exec('from ' + modul + ' import *')
### debug prints: ####
if ('myfunc' in dir(modul) and modul.isfunction(modul.myfunc)):
print('myfunc is defined as function in modul ', modul)
if modul in sys.modules:
print(modul, 'was imported successfully')
else:
print(modul, 'was not imported')
try:
myfunc
except NameError:
print("myfunc not in scope!")
else:
print("myfunc in scope!")
The variation in the import methods did not matter. The code would consistently print "myfunc not in scope" or yield a NameError
if I just try to run myfunc
.