Skip to content

Unexpected behavior in lambda fn + list comprehension - scoping bug? #92269

Closed
@khusmann

Description

@khusmann

Bug report

When I use a list comprehension to construct a list of lambda functions, I end up with duplicates of the function created with the last value of the comprehension. MWE:

def fun(value: int):
    print(value)

def setup_fns():
    return [lambda: fun(v) for v in range(1, 5)]

for i in setup_fns():
    i()

I would expect this to print the values 1,2,3,4 but instead I get 4,4,4,4

If I add a layer of indirection, the list comprehension works as expected and it will print 1,2,3,4:

def helper(v: int):
    return lambda: fun(v)

def setup_fns2():
    return [helper(v) for v in range(1, 5)]

for i in setup_fns2():
    i()

Thanks for looking in to this. Sorry if this isn't a bug and I'm just not understanding something about the scoping on list comprehensions. I found it very surprising.

Your environment

  • CPython versions tested on: Python 3.10.2 (condaforge), Python 3.8.10 (Ubuntu 20.04.2 LTS)
  • Operating system and architecture: Ubuntu 20.04.2 LTS

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions