Skip to content

Instantly share code, notes, and snippets.

@izmailoff
Created September 30, 2021 01:51
Show Gist options
  • Save izmailoff/4b23902ffcb9cf8ebf40465711420566 to your computer and use it in GitHub Desktop.
Save izmailoff/4b23902ffcb9cf8ebf40465711420566 to your computer and use it in GitHub Desktop.
Python closures are dangerous
# SCALA
scala> val fs = List(1, 2, 3).map(i => () => i)
val fs: List[() => Int] = List($Lambda$2341/0x00000008408e7c40@64518270, $Lambda$2341/0x00000008408e7c40@3b7c58e7, $Lambda$2341/0x00000008408e7c40@79627d27)
scala> fs.foreach(x => println(x()))
1
2
3
--------
# PYTHON
fs = []
for i in range(3):
c = i
fs.append(lambda: c)
fs
Out[5]:
[<function __main__.<lambda>()>,
<function __main__.<lambda>()>,
<function __main__.<lambda>()>]
for f in fs:
print(f())
2
2
2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment