dynamically generated runtime methods & reflection

Josiah Carlson josiah.carlson at sbcglobal.net
Thu Jun 14 08:30:07 CEST 2007


Jay Loden wrote:
> Hi all,
> 
> First, apologies if anyone gets this twice, but it took me quite a
> while to figure out that Python.org is evidently rejecting all mail
> from my mail server because I don't have reverse DNS configured.
> Anyway:
> 
> I'm not even sure how to phrase this question properly or the right
> terminology on this so bear with me. What I'm looking to find out is
> 
> a) is there a functionality in Python where I can call a method I have
> not defined ahead of time, and based on the method name, change the
> functionality of the method at runtime?

Yes.  Implement a __getattr__ method on your class (which you mention).

> b) if not, what is the "Pythonic" approach to the problem outlined
> below? Any recommendations on how to approach the problem differently
> are welcome.
> 
> I've googled and read my Python reference pretty extensively and I've
> found some hints but nothing that really answered my questions, so
> here I am  :-)  I did figure out that you can overload __getattr__ in
> a clas to define a new method at runtime, but I got stuck when I
> couldn't figure out how to have a method know what name it was
> originally called with. That's the basic question, see below for the
> context I'm asking the question in and *why* I want to do the above
> :-)

Ahh, so you want to pass the method name to the method that you are 
returning to be called.  No problem.

 >>> import functools
 >>>
 >>> class foo:
...     def __getattr__(self, name):
...         return functools.partial(self.ActualMethod, name)
...
...     def ActualMethod(self, name, *args, **kwargs):
...         #handle *args and **kwargs based on name!
...         print name, args, kwargs
...
 >>> foo().bar('hello', world=1)
bar ('hello',) {'world': 1}
 >>>


  - Josiah



More information about the Python-list mailing list