Instantiate nested Cmd Interpreter in Python
<p>Hi I'm looking to create a nested interpreter in Python using the Cmd module.</p>

<p>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).</p>

<p>My nested interpreter is currently setup like this:</p>

<pre><code>def instantiateConsole(base):

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

        def do_action(self,args):
            print "Action"
    return SubConsole
</code></pre>

<p>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.</p>

<p>Is there any workaround to this?</p>

<p>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.</p>

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

<p>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 <code>instantiateClass</code>. In the simplest case you can just add a standard directory where these modules will live to your <code>sys.path</code>, import the module by name and then extract the base class (which I assume for the purpose of simplicity will always be defined as <code>BaseConsole</code>). You would then run code such as</p>

<pre><code>extension_module = importlib.import_module("my_extension")
new_console = instantiateConsole(extension_module.BaseConsole)
</code></pre>

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

python python-cmd