What lambda itself does:

This answer explains how to create test cases dynamically.

Answer Code:

class Tests(unittest.TestCase):
    def check(self, i, j):
        self.assertNotEquals(0, i-j)

for i in xrange(1, 4):
    for j in xrange(2, 6):
        def ch(i, j):
            return lambda self: self.check(i, j)
        setattr(Tests, "test_%r_%r" % (i, j), ch(i, j))

I tested and it works, but I can’t just understand how?

It's hard for me to understand the magic lambda self:here, basically:

  • Is lambda used to accomplish the exact opposite functools.partial()(i.e. to create a wrapper function with one additional parameter that is not yet known).
  • Is a selfmeaningful keyword or will it lambda spamwork just as well?
  • What is lambda score?
  • How is it that it is .check()perfectly outside the classes area?
  • ? - , lambda ( , , :)
+5
3

: , i j.

:

for i in xrange(1, 4):
    for j in xrange(2, 6):
        setattr(Tests, "test_%r_%r" % (i, j), lambda self: self.check(i, j))

, , lambdas i j . , , i j , .

, i j . itertools.product, :

from itertools import product
from operator import methodcaller

for i, j in product(range(1, 4), range(2, 6)):
  setattr(Tests, "test_%r_%r" % (i, j),
          lambda self, i=i, j=j: self.check(i, j))

functools.partial() (.. , )

. check(i, j) , . Tests.

?

spam . self - , .

?

test_[i]_[j]() Tests.

.check() ?

, Tests self.

+3

lambda . self - , j

, ch (i, j) j, self.

self , Python - , . , .

  • . Tests , check_i_j

  • j,

  • , self, , , , self

+3

a_function = lambda x: do_something_with(x)

def a_function(x):
    return do_something_with(x)

- . , , :

class Tests:
...
   test_1_2 = lambda self: self.check(1, 2)

:

class Tests:
...
   def test_1_2(self):
       return self.check(1, 2)

, , setattr.


  • , functools.partial() (.. , )

, . partial .

test_1_2 = lambda self: self.check(1, 2)

test_1_2 = partial(Tests.check, i=1, j=2)
  • ?

. self, . , .

  • lambda?

lambda , , .

  • How is .check () different than class scope?

This is not true. He self.check(), where selfis an instance of the class Tests.

+2
source

All Articles