0

Hi I'm looking to create a nested interpreter in Python using the Cmd module.

I set up a dynamic module loading because I want my project to be easily expandable (i.e. add a new python file into a folder and without changing the main code being able to load it).

My nested interpreter is currently setup like this:

def instantiateConsole(base):

    class SubConsole(cmd.Cmd, base):
        def __init__(self):
            cmd.Cmd.__init__(self)

        def do_action(self,args):
            print "Action"
    return SubConsole

This is necessary because in order to create a nested interpreter I have to pass the MainConsole as a second variable to the SubConsole class. The problem with this is that this way I can only create classes inside this method and I won't be able to add a new console module file that I can load dynamically without having the definition inside this method.

Is there any workaround to this?

ptr0x01
  • 627
  • 2
  • 10
  • 25

1 Answers1

0

When you say "pass the MainConsole as a second variable" you appear to mean "make the new SubConsole a subclass of the MainConsole". You are effectively defining a class factory that takes the base class as an argument.

You say "create classes inside this method", but instantiateConsole in a function, it appears. It's important to be careful about terminology.

None of this is anything to do with dynamic import of (the modules containing) other base classes that you may wish to use as arguments to instantiateClass. In the simplest case you can just add a standard directory where these modules will live to your sys.path, import the module by name and then extract the base class (which I assume for the purpose of simplicity will always be defined as BaseConsole). You would then run code such as

extension_module = importlib.import_module("my_extension")
new_console = instantiateConsole(extension_module.BaseConsole)

If the name of the base class can vary (how would you determine its name?) you might have to use getattr() in preference to simple attribute access to the dynamically imported extension module.

holdenweb
  • 33,305
  • 7
  • 57
  • 77