472,101 Members | 1,577 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,101 software developers and data experts.

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 1617
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
reply views Thread by leo001 | last post: by

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.