0

A small code snippet from python 3.7.6 which completely has blown my mind:

def func(e, k):
    print(k + e)

for f in [lambda e: func(e, k) for k in ['T', 'E', 'K']]:
    for e in range(3):
        f(str(e))

As an output I get:

K0
K1
K2
K0
K1
K2
K0
K1
K2

Is it a bug or a feature of Python? Because if you replace lambda with functools.partial everything works as expected!

  • 5
    And what does it mean "as expected"? What would you like to see as output and how exactly the code with `functools.partial` looks like? – sophros Jan 31 '20 at 10:52
  • 2
    I would recommend to check out [Late Binding Closures](https://docs.python-guide.org/writing/gotchas/#late-binding-closures) – Abdul Niyas P M Jan 31 '20 at 10:52
  • Expectation is subjective, but the behaviour is as documented, there is a dupe somehwere – Chris_Rands Jan 31 '20 at 10:55

0 Answers0