Adding code and methods to a class dynamically

Sarir Khamsi sarir.khamsi at raytheon.com
Thu Jul 28 13:32:23 EDT 2005


I have a class (Command) that derives from cmd.Cmd and I want to add
methods to it dynamically. I've added a do_alias() method and it would
be nice if I could turn an alias command into a real method of Command
(that way the user could get help and name completion). The code would
be generated dynamically from what gets passed to the do_alias()
method. I've tried looking in the Python cookbook and have tried:

def funcToMethod(func, clas, method_name=None):
   setattr(clas, method_name or func.__name__, func)

class Command(object, cmd.Cmd):
   # ...
   def do_f1(self, rest): print 'In Command.do_f1()'
   def do_alias(self, rest):
      rest.strip() # remove leading and trailing whitespace
      pat = re.compile(r'^(\w+)\s+(\w+)$')
      mo = pat.search(rest)
      if mo:
         newName = mo.group(1)
         existingName = mo.group(2)
         code = 'def do_' + newName + '(self, rest):\n'
         code += '   self.do_' + existingName + '(rest)\n'
         exec code
         funcToMethod(getattr(newModule, 'do_' + existingName),
                      self,
                      'do_' + 'existingName')
      else:
         print 'Invalid alias command'

but this does not seem to work. What I get is:

$ importDynamic.py
(Cmd) do alias x f1
*** Unknown syntax: do alias x f1
(Cmd) 

Any suggestions? Thanks.

Sarir



More information about the Python-list mailing list