missing argument when using importlib to create a class at runtime

Question:

I want to load a Python file (module) dynamically when the user inputs the filename (here for example: RegionOfInterest.py). In the file will be one class (here: RegionOfInterest). All classes have a method with the same name (here: start) which I want to call.

This works fine, but if I call another method from the start method I get an error:

TypeError: testMethod() missing 1 required positional argument: 'self'

Minimal Working Example:

main.py:

import importlib

if __name__ == '__main__':
    module_name = "RegionOfInterest"    # will be user input
    class_name = module_name            # same as module_name

    myModule = importlib.import_module(f"{module_name}")
    myClass = myModule.__getattribute__(class_name)
    myClass.__init__(myClass)           # apparently is not called automatically ?
    myMethod = myClass.__getattribute__(myClass, "start")
    myMethod(myClass)

RegionOfInterest.py:

class RegionOfInterest:

    def start(self):
        self.testMethod()

    def testMethod(self):
        pass
Asked By: ImNotARobot

||

Answers:

I’m not sure what you’re trying to achieve with this code:

myClass.__init__(myClass, img)
myMethod = myClass.__getattribute__(myClass, "start")
myMethod(myClass)

myClass is a class, not an instance of that class. So your passing an invalid object as self to the __init__() method.

The following seems much simpler to me and does work without the error:

import importlib

module_name = 'RegionOfInterest'
class_name = module_name

module = importlib.import_module(module_name)
Class = getattr(module, class_name)
obj = Class()
obj.start()

NB: I replaced object.__getattribute__() by getattr(), although I think both should work for your specific situation. I also changed the naming to follow PEP-8.

Answered By: wovano
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.