473,583 Members | 3,386 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Adding code and methods to a class dynamically

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(fu nc, clas, method_name=Non e):
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(ge tattr(newModule , 'do_' + existingName),
self,
'do_' + 'existingName')
else:
print 'Invalid alias command'

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

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

Any suggestions? Thanks.

Sarir
Jul 28 '05 #1
5 2244
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(fu nc, clas, method_name=Non e):
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(ge tattr(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
Jul 28 '05 #2
Peter Hansen <pe***@engcorp. com> writes:
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)


Thanks, this is amazingly more simple than what I had. This works
fine but I'm looking at the code for cmd and don't really see how you
get completion to work on the new alias.

Also, I would like the alias to have arguments:

alias newName existingName arg1 arg2 ...

Currying comes to mind, but I haven't tried it yet. Thanks again for
the help.

Sarir
Jul 28 '05 #3
Sarir Khamsi wrote:
Thanks, this is amazingly more simple than what I had. This works
fine but I'm looking at the code for cmd and don't really see how you
get completion to work on the new alias.
I'm not sure what "completion " means in this case, and I'm not aware of
any "command-line completion" support in cmd.Cmd though it may well be
there, so I can't say. Certainly there is nothing in any way different
about the new attribute created by the alias code, as both it and the
original attribute are bound to exactly the same method.
Also, I would like the alias to have arguments:
alias newName existingName arg1 arg2 ...

Currying comes to mind, but I haven't tried it yet. Thanks again for
the help.


It sounds like currying, but I'd suggest implementing such a thing with
a completely separate layer on top of the existing Cmd stuff, probably
through overriding .default() and doing a lookup in a dictionary, then
building a command line with the original command and maybe executing it
with .onecmd() if that can work from within the .cmdloop(). Lots of
possibilities there; haven't tried any myself.

-Peter
Jul 29 '05 #4
Peter Hansen <pe***@engcorp. com> writes:
I'm not sure what "completion " means in this case, and I'm not aware
of any "command-line completion" support in cmd.Cmd though it may well
be there, so I can't say. Certainly there is nothing in any way
different about the new attribute created by the alias code, as both
it and the original attribute are bound to exactly the same method.


If you have the readline module, you get TAB command completion for
free (a la bash, emacs, etc)...or maybe readline only gives you
emacs-style command history editing, or both...not sure.
Jul 29 '05 #5
Sarir Khamsi wrote:
Peter Hansen <pe***@engcorp. com> writes:
I'm not sure what "completion " means in this case, and I'm not aware
of any "command-line completion" support in cmd.Cmd though it may well
be there, so I can't say. Certainly there is nothing in any way
different about the new attribute created by the alias code, as both
it and the original attribute are bound to exactly the same method.


If you have the readline module, you get TAB command completion for
free (a la bash, emacs, etc)...or maybe readline only gives you
emacs-style command history editing, or both...not sure.


Cool. The answer to whether a particular approach preserves command
completion ability then, unfortunately, depends on how it's implemented.
If it's totally dynamic, then the aliases my approach created will be
supported, but if it's done at Cmd creation time, or in some other
static manner, the dynamically created aliases won't be found.

-Peter
Jul 29 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2446
by: marco | last post by:
hi I've got a class "myClass" ... and i CAN'T EXTENDS this class! But i can add NEW methods to "myClass", like that : method = new.instancemethod( myNewMethod , None, myClass) myClass.__dict__ = method i'd like to add NEW attributs to "myClass" ... i'm pretty sure it's possible (with "get/set-attr") ... but i don't know how
5
1488
by: damian birchler | last post by:
Hello there! I'm wondering if it is possible to automatically dynamically add methods to a class instance. For example, if there is a class Foo with one method named add_function and an instance of Foo f - class Foo: add_function(self, name, args): # ...
4
2368
by: Max Derkachev | last post by:
Good day to all. Some time ago I'd been playing with a framework which uses dynamic class creation havily. Say, I could do: class A: pass # I method name is dynamic meth_name = 'foo'
8
2934
by: Kevin Little | last post by:
#!/usr/bin/env python ''' I want to dynamically add or replace bound methods in a class. I want the modifications to be immediately effective across all instances, whether created before or after the class was modified. I need this to work for both old ('classic') and new style classes, at both 2.3 and 2.4. I of course want to avoid...
11
2283
by: Steven D'Aprano | last post by:
Suppose I create a class with some methods: py> class C: .... def spam(self, x): .... print "spam " * x .... def ham(self, x): .... print "ham * %s" % x .... py> C().spam(3) spam spam spam
3
1919
by: Gabriele *darkbard* Farina | last post by:
Hi, there is a way to add methods to an object dynamically? I need to do something like this. I remember python allowed this ... class A(object): def do(s, m): print m @staticmethod def init(obj): obj.do = A.do
3
4866
by: Jim Heavey | last post by:
Trying to figure out the technique which should be used to add rows to a datagrid. I am thinking that I would want an "Add" button on the footer, but I am not quite sure how to do that. Is that the best method? Do you have a sample of how to do this?
9
1376
by: Mike | last post by:
I was messing around with adding methods to a class instance at runtime and saw the usual code one finds online for this. All the examples I saw say, of course, to make sure that for your method that you have 'self' as the first parameter. I got to thinking and thought "I have a lot of arbitrary methods in several utility files that I might...
0
1100
by: Gabriel Genellina | last post by:
En Tue, 29 Jul 2008 01:17:13 -0300, Piyush Anonymous <piyush.subscription@gmail.comescribi�: You forget the self argument (this explains the error you got). It's a lot easier than that; just add the *function* object to the class namespace: setattr(clas, method_name, func)
0
7894
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8172
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8320
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7929
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6577
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5697
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5370
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
2328
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1424
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.