Buggy python behavior related to for loop and higher-order functions [duplicate]
I'd like to ask about the behavior of python.
I am using python 3.10.8. I wrote the following code:
from typing import Callable
def buggy_swap_function_args(fs: list[Callable[[str, str], str]]):
swaped_fs: list[Callable[[str, str], str]] = []
for f in fs:
开发者_如何学Python swaped_fs.append(lambda x, y: f(y, x))
return swaped_fs
fs = [lambda x,y: "1" + x + y, lambda x,y: "2" + x + y, lambda x,y: "3" + x + y]
swapped_fs = buggy_swap_function_args(fs)
for swapped_f in swapped_fs:
print(swapped_f("a", "b"))
In my understanding, this program should print as follows:
1ba
2ba
3ba
However, the above program printed as follows:
3ba
3ba
3ba
I re-wrote as follows and obtained the desired print:
def swap_function_args(fs: list[Callable[[str, str], str]]):
swaped_fs: list[Callable[[str, str], str]] = []
def g(f: Callable[[str, str], str]) -> Callable[[str, str], str]:
def h(x: str, y: str) -> str:
return f(y, x)
return h
for f in fs:
swaped_fs.append(g(f))
return swaped_fs
fs = [lambda x,y: "1" + x + y, lambda x,y: "2" + x + y, lambda x,y: "3" + x + y]
swapped_fs = swap_function_args(fs)
for swapped_f in swapped_fs:
print(swapped_f("a", "b"))
I think the above two functions are completely the same. What's the difference between them? Is this a bug in python?
精彩评论