Skip to content

Instantly share code, notes, and snippets.

@nhomar
Forked from moylop260/cell_var_from_loop_bad_case.py
Last active November 6, 2017 00:59
Show Gist options
  • Save nhomar/838cdd866064df59f05a6207f9efc51c to your computer and use it in GitHub Desktop.
Save nhomar/838cdd866064df59f05a6207f9efc51c to your computer and use it in GitHub Desktop.
from __future__ import print_function
def bad_case():
"""Closing over a loop variable."""
lst = []
dct = {}
for i in range(10):
meth = i
print([meth for meth in g_lst]) # good case if you use the meth and is not used anymore
return meth
g_lst = bad_case()
print(bad_case()) # bad case if you use the meth after, because it will have the same value in all lambda methods.
# Results:
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment