469,282 Members | 1,779 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,282 developers. It's quick & easy.

How best to dynamically define methods (and functions)?

I can see an obvious but hacky way to define a Python function at
runtime. I can't see any obvious way to add a method to a class at
runtime (though I'm sure one could do just about anything by digging
into the metaclass stuff, which I will do if needed). But pointers to
cleaner or easier existing ways to do this would be most appreciated.

In case it's of interest in the context of the question, I need to
define a largish set of functions (and similar methods) that define a
XML-type markup language. Most of these functions will just be of the form

def fun(...):
return Node('fun', ...)

so it'd definitely be nice to just create most of them automatically,
and only do the special cases by hand.
Many thanks,
Ken
Sep 2 '07 #1
1 1529
Kenneth McDonald schrieb:
I can see an obvious but hacky way to define a Python function at
runtime. I can't see any obvious way to add a method to a class at
runtime (though I'm sure one could do just about anything by digging
into the metaclass stuff, which I will do if needed). But pointers to
cleaner or easier existing ways to do this would be most appreciated.

In case it's of interest in the context of the question, I need to
define a largish set of functions (and similar methods) that define a
XML-type markup language. Most of these functions will just be of the form

def fun(...):
return Node('fun', ...)

so it'd definitely be nice to just create most of them automatically,
and only do the special cases by hand.
Then don't do it that way, but use __getattr__. It will exactly do what
you want:
class Foo(object):
def __getattr__(self, name):
return Node(name, ....)
def some_node(self):
... # hand coded stuff
Diez
Sep 2 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

14 posts views Thread by Blue Ocean | last post: by
8 posts views Thread by Kevin Little | last post: by
11 posts views Thread by Steven D'Aprano | last post: by
10 posts views Thread by jojobar | last post: by
41 posts views Thread by Jim | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.