473,473 Members | 1,488 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to code dynamically created methods?

kj


I've tried a bazillion ways to code dynamically generated methods,
to no avail.

The following snippet is a very simplified (and artificial) demo
of the problem I'm running into, featuring my latest attempt at
this. The idea here is to use __getattr__ to trap any attempt to
invoke a nonexistent method, have it return a generic handler called
_auto which creates the new method dynamically, invokes it, and
"installs" it in the class, so that subsequent calls to the same
method go directly to the newly created method, instead of to
__getattr__. It is this last step, the "installation" of the new
method, that is giving me problems.
class A( object ):
def __getattr__( self, name ):
self._auto_name = name
return self._auto

def hello( self, name ):
print "hi! my name is %s" % name

def _auto( self, *args ):
name = self._auto_name
def m( self, *args ): self.hello( name )
m( self, *args )

m = classmethod( m )
setattr( A, name, m )

x = A()
x.foo() # ok
x.foo() # bombs

>>reload(test) hi! my name is foo Traceback (most recent call
last):
File "<stdin>", line 1, in ? File "test.py", line 19, in ?
x.foo() File "test.py", line 12, in m
self.hello( name ) TypeError: unbound method hello() must be
called with A instance as first argument (got str instance instead)
>>>
I'm sure that the problem is with my naive attempt to add a method
to class A dynamically (in the last two lines of the definition of
_auto). What's the right way to do this?

Thanks!

kj

--
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
Jun 20 '07 #1
3 1461
kj

Nevermind, I found the problem...

Thanks,

kj

In <f5**********@reader2.panix.comkj <so***@987jk.com.invalidwrites:
>I've tried a bazillion ways to code dynamically generated methods,
to no avail.
>The following snippet is a very simplified (and artificial) demo
of the problem I'm running into, featuring my latest attempt at
this. The idea here is to use __getattr__ to trap any attempt to
invoke a nonexistent method, have it return a generic handler called
_auto which creates the new method dynamically, invokes it, and
"installs" it in the class, so that subsequent calls to the same
method go directly to the newly created method, instead of to
__getattr__. It is this last step, the "installation" of the new
method, that is giving me problems.
>class A( object ):
def __getattr__( self, name ):
self._auto_name = name
return self._auto
def hello( self, name ):
print "hi! my name is %s" % name

def _auto( self, *args ):
name = self._auto_name
def m( self, *args ): self.hello( name )
m( self, *args )
m = classmethod( m )
setattr( A, name, m )
>x = A()
x.foo() # ok
x.foo() # bombs
>>>reload(test) hi! my name is foo Traceback (most recent call
last):
File "<stdin>", line 1, in ? File "test.py", line 19, in ?
x.foo() File "test.py", line 12, in m
self.hello( name ) TypeError: unbound method hello() must be
called with A instance as first argument (got str instance instead)
>>>>
>I'm sure that the problem is with my naive attempt to add a method
to class A dynamically (in the last two lines of the definition of
_auto). What's the right way to do this?
>Thanks!
>kj
>--
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
--
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
Jun 20 '07 #2
kj <so***@987jk.com.invalidwrites:
Nevermind, I found the problem...
Please share the solution with the list, if you would.

--
\ "I must say that I find television very educational. The minute |
`\ somebody turns it on, I go to the library and read a book." -- |
_o__) Groucho Marx |
Ben Finney
Jun 20 '07 #3

kj wrote:
>
I've tried a bazillion ways to code dynamically generated methods,
to no avail.

The following snippet is a very simplified (and artificial) demo
of the problem I'm running into, featuring my latest attempt at
this. The idea here is to use __getattr__ to trap any attempt to
invoke a nonexistent method, have it return a generic handler called
_auto which creates the new method dynamically, invokes it, and
"installs" it in the class, so that subsequent calls to the same
method go directly to the newly created method, instead of to
__getattr__. It is this last step, the "installation" of the new
method, that is giving me problems.
class A( object ):
def __getattr__( self, name ):
self._auto_name = name
return self._auto

def hello( self, name ):
print "hi! my name is %s" % name

def _auto( self, *args ):
name = self._auto_name
def m( self, *args ): self.hello( name )
m( self, *args )

m = classmethod( m )
setattr( A, name, m )

x = A()
x.foo() # ok
x.foo() # bombs
I tried to do the same exact thing recently and got my answer from the mailing list. Here's the test code I got working using the help from the list:

#!/usr/bin/python

import functools

class TestClass:
def __init__(self):
pass

def __getattr__(self, name):
try:
return getattr(self.__class__, name)
except AttributeError:
return functools.partial(self.foo, name)

def foo(self, name, **args):
print name
for i in args:
print " %s=%s" % (i, args[i])

def bar(self):
print "bar()"

test = TestClass()
test.someMethod()
test.anotherMethod()
test.someMethod()
test.bar()

Hope that helps,

-Jay
Jun 21 '07 #4

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

Similar topics

4
by: Gurry | last post by:
Hi there I would like to write a javascript function that creates a drop-down list dynamically. I read on the docs that most HTML controls can not be created on run-time. what kind of...
5
by: Sarir Khamsi | last post by:
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...
1
by: engwar | last post by:
Not really sure how to ask this. I'm new to CSS/DHTML I want to create something similar to how yahoo and gmail handle the "to" field when you type an email. If you start typing "d" you will...
4
by: Jeronimo Bertran | last post by:
This may be a very simple question. I have some old java code that uses scripting to dynamically create a <MAP> in my HTML. <map name="Map"> <script> var i; for (i=0; i<arr.length; i++)
6
by: Earl Teigrob | last post by:
I am writing an application that dynamically loads user controls at run time based on user options. I would like to give my users the ability to build their own user controls and add them to my...
18
by: Joe Fallon | last post by:
I have some complex logic which is fairly simply to build up into a string. I needed a way to Eval this string and return a Boolean result. This code works fine to achieve that goal. My...
2
by: accyboy1981 | last post by:
Hi, I'm creating an asp text box dynamically within an asp table. I know the id as this is not dynamic (txBxPass). I need to get the text of this text box when an asp button is pressed. I know...
3
by: Bart Van Hemelen | last post by:
I'm working on a project where the user of a site will receive custom content, depending on a set of parameters. The content will all be contained in UserControls (.ascx), that will be used as...
4
by: mohaaron | last post by:
I can think of a lot of reasons why this might need to be done but as far as I can tell it's not possible. I've been looking for a way to add HtmlTableRows to a table using a button click for a...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
1
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...
1
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...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.