Hi all, I want to generate some methods in a class using setattr and lambda. Within each generated function a name parameter to the function is replaced by a string constant, to keep trail which function was called. The problem I have is, that the substituted name parameter is not replaced by the correct name of the function, but by the last name the for loop has seen.
import unittest class WidgetDummy: '''This class records all calls to methods to an outer list''' def __init__( self, name, calls ): '''name is the name of the object, which gets included into a call record. calls is the list where the calls are appended.''' self.name = name self.calls = calls for fn in ( 'Clear', 'Append', 'foobar' ): func = lambda *y,**z: self.__callFn__( fn, y, z ) setattr( self, fn, func ) def __callFn__( self, fnName, *args ): '''Add the function call to the call list''' self.calls.append( ( self.name, fnName, args ) ) class Testcase( unittest.TestCase ): def testFoo( self ): calls = [] wd = WidgetDummy( 'foo', calls ) wd.Append( 23 ) self.assertEqual( [ ( 'foo', 'Append', ( 23, {} ) ) ], calls ) unittest.main() -- GPG encrypted mails preferred. GPG verschlüsselte Mails bevorzugt. ---> http://chaosradio.ccc.de/media/ds/ds085.pdf Seite 20 <---- -- http://mail.python.org/mailman/listinfo/python-list