Skip to content

Instantly share code, notes, and snippets.

@kristof-mattei
Last active October 29, 2021 18:02
Show Gist options
  • Save kristof-mattei/ce11ef1cac67bfa787c9e145824845ef to your computer and use it in GitHub Desktop.
Save kristof-mattei/ce11ef1cac67bfa787c9e145824845ef to your computer and use it in GitHub Desktop.
Comparing lambda closure capturing in Python and javascript
# sorry, python doesn't have a built-in table printer
from tabulate import tabulate
max = 3
def get_functions():
lst = []
for i in range(0, max):
lst.append(lambda: i)
return lst
def get_functions_yield():
for i in range(0, max):
yield lambda: i
def get_functions_yield_separate_var():
for i in range(0, max):
x = i
yield lambda: x
def get_functions_yield_separate_context():
for i in range(0, max):
yield (lambda x: lambda: x)(i)
def for_f(iterator):
for f in iterator():
yield f()
def for_f_preload(iterator):
for f in list(iterator()):
yield f()
# functions:
functions = [
get_functions,
get_functions_yield,
get_functions_yield_separate_var,
get_functions_yield_separate_context,
]
# iterations
iterations = [
for_f,
for_f_preload
]
headers = ["(index)"]
rows = []
for f in functions:
headers.append(f.__name__)
for i in iterations:
row = []
rows.append(row)
row.append(i.__name__)
for f in functions:
row.append(list(i(f)))
print(tabulate(rows, headers=headers, tablefmt="grid"))
@kristof-mattei
Copy link
Author

Prints

+---------------+-----------------+-----------------------+------------------------------------+----------------------------------------+
| (index)       | get_functions   | get_functions_yield   | get_functions_yield_separate_var   | get_functions_yield_separate_context   |
+===============+=================+=======================+====================================+========================================+
| for_f         | [2, 2, 2]       | [0, 1, 2]             | [0, 1, 2]                          | [0, 1, 2]                              |
+---------------+-----------------+-----------------------+------------------------------------+----------------------------------------+
| for_f_preload | [2, 2, 2]       | [2, 2, 2]             | [2, 2, 2]                          | [0, 1, 2]                              |
+---------------+-----------------+-----------------------+------------------------------------+----------------------------------------+

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment