Tuesday, January 20, 2009

A Python Trick: Adding a Lambda Method to a Class

It does not take much to add a lambda function to a Python class. For example, consider the following:

>>> class A: pass
>>> f = lambda self,x:x
>>> setattr(A,"f",f)

This code adds the method f to class A. For example:

>>> a=A()
>>> a.f(1)
1

However, the f method created this way does not have the expected Python name:

>>> A.f.__name__
''

Further, defining this value is not possible; the instancemethod f does not have a __name__ attribute.

The trick is to name the lambda function before defining the class method:

>>> class A: pass
>>> f = lambda self,x:x
>>> f.__name__ = "f"
>>> setattr(A,"f",f)
>>> f.__name__
'f'

This is simple, but it took too long to figure this out...

1 comment: