Adding code and methods to a class dynamically
Peter Hansen
peter at engcorp.com
Thu Jul 28 14:00:17 EDT 2005
Sarir Khamsi wrote:
> 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.
If it's truly just an alias you want, then something like this should
work better. Replace everything in the if mo: section with this:
if mo:
newName = mo.group(1)
existingName = mo.group(2)
existingMethod = getattr(self, 'do_' + existingName)
setattr(self, 'do_' + newName, existingMethod)
-Peter
More information about the Python-list
mailing list