How best to dynamically define methods (and functions)?

Kenneth McDonald kenneth.m.mcdonald at sbcglobal.net
Sat Sep 1 23:35:44 EDT 2007


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



More information about the Python-list mailing list