Created
September 30, 2021 01:51
-
-
Save izmailoff/4b23902ffcb9cf8ebf40465711420566 to your computer and use it in GitHub Desktop.
Python closures are dangerous
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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