dynamically generated runtime methods & reflection

Josiah Carlson josiah.carlson at sbcglobal.net
Thu Jun 14 21:12:11 CEST 2007


Jay Loden wrote:
> Josiah Carlson wrote:
>> 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}
>>  >>>
> 
> Thanks, this is exactly what I was looking for! For some reason functools didn't even show up at all during Google searches...must have just had the wrong search terms.

Well, the particular operation is typically called 'currying a 
function', and unless you know what to look for, it isn't very easy to 
make happen.

On the other hand, it is also relatively easy to implement by hand if 
necessary.

  - Josiah



More information about the Python-list mailing list