0

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.

SunnyM
  • 31
  • 5
  • There is an elegant solution which I have done in the past, but I see is not deprecated. Have you seen https://stackoverflow.com/questions/19009932/import-arbitrary-python-source-file-python-3-3 – blueteeth Dec 10 '19 at 12:41
  • In the past I have used https://docs.python.org/2/library/imp.html#imp.load_source – blueteeth Dec 10 '19 at 12:42
  • @blueteeth I read a bit about the importlib solution, it seemed to me a bit over the top, but I might try it in the end.. – SunnyM Dec 10 '19 at 15:56
  • @blueteeth Thank you! – SunnyM Dec 10 '19 at 18:09

1 Answers1

0

In the end I didn't find a way to make the import within the class method. I had to put it in the global scope and import the function itseld to the class method.

It's not the elegant solution I was looking for - but seemed to be the only way to make it work.

SunnyM
  • 31
  • 5