Last active
October 29, 2021 18:02
-
-
Save kristof-mattei/ce11ef1cac67bfa787c9e145824845ef to your computer and use it in GitHub Desktop.
Comparing lambda closure capturing in Python and javascript
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
# 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")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prints