473,785 Members | 2,772 Online
Bytes | Software Development & Data Engineering Community
+ 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 "installati on" 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 1476
kj

Nevermind, I found the problem...

Thanks,

kj

In <f5**********@r eader2.panix.co mkj <so***@987jk.co m.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 "installati on" 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(tes t) 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.co m.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 "installati on" 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__(sel f, name):
try:
return getattr(self.__ class__, name)
except AttributeError:
return functools.parti al(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.anotherMet hod()
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
3702
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 work-arounds do you use in this case? maybe DHTML? do you have any example ? Javascript allows you to create the options of the drop-down list dynamically but not the drop-down list itself, I believe. Actually the same question goes for any other HTML...
5
2254
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 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,...
1
1735
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 see a list of all the the people in your address book whos last names start with "d". Type another letter "e" for example and the list is narrowed to people who's names start with "de". etc etc.
4
1947
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
2583
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 user control folder so that they can be selected and loaded at run time also. These new controls will need to have access to many of the classes with there properties and methods within the complied code. Is this possible? This seems to be the...
18
3163
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 question is what happens to the dynamically created assembly when the method is done running? Does GC take care of it? Or is it stuck in RAM until the ASP.Net process is recycled? This code executes pretty frequently (maybe 4 times per transaction) and...
2
1687
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 that I need to recursively go through the controls on the page but I'm having troble with this. I think that the problem is that the control is within another control (i.e. the text box being in the table). I've created two methods but neither...
3
2129
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 webparts on a page. We need to add the webparts dynamically to the site, depending on the status of the user: this involves a personalisation of a travel website, so a user can be "before" a trip, "during" a trip and "after" a trip, and depending...
4
2976
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 while and it seems it's not possible because the row that gets added with each click won't get recreated after a post back. After all the reading it seems that any dynamically created controls must be created in the Init event to be recreated after...
0
10319
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10087
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8971
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7496
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4046
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
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2877
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.