Search code examples
pythonreferencesetattr

Using setattr to freeze some parameters of a method


in order to automatically generate parameterized tests, I am trying to add methods to a class in by freezing some parameters of an existing method. Here is the piece of Python 3 code

class A:
    def f(self, n):
        print(n)

params = range(10)

for i in params:
    name = 'f{0}'.format(i)
    method = lambda self: A.f(self, i)
    setattr(A, name, method)

However, the following lines then produce rather disappointing output

a = A()
a.f0()

prints "9" (instead of "0"). I must be doing something wrong, but I can't see what. Can you help ?

Thanks a lot


Edit: this question is indeed a duplicate. I would like to acknowledge the quality of all comments, which go much deeper than the raw answer.


Solution

  • Try

    method = lambda self, i=i: A.f(self, i)
    

    because otherwise when you call the method i's value may have changed