How best to dynamically define methods (and functions)?

Erik Max Francis max at alcyone.com
Sat Sep 1 23:51:05 EDT 2007


Kenneth McDonald wrote:

> 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.

Something like::

	method = ['fun', ...]
	for method in methods:
	    setattr(MyClass, method, lambda *x: Node(method, *x))

The first argument here will be the implicit self, if you don't want 
that, strip off the first argument (or use lambda self, *x: ...).

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   I like young girls. Their stories are shorter.
    -- Thomas McGuane



More information about the Python-list mailing list