warning : cell-var-from-loop
bing解释
for i in range(10): f = lambda i:i print(f())
The warning message cell-var-from-loop
is emitted by Pylint, a Python code analysis tool. This warning is raised when a variable is defined inside a loop and used in a closure.
The warning message indicates that this will result in all closures using the same value for the closed-over variable ².
In your code, the warning message is raised because the variable i
is defined inside a loop and used in a closure.
To fix this warning, you can use a lambda function as a closure and pass the value of i
as a parameter to the lambda function. Here is an example of how you can modify your code:
for i in range(10): f = lambda x=i: x print(f())
In this example, the lambda function takes i
as a parameter and returns its value.
By doing so, the value of i
is passed to the lambda function as a parameter and each closure uses a different value for the closed-over variable.
example
# task.add_done_callback(lambda futrue: self.get_image_url(futrue, i, li)) task.add_done_callback(lambda futrue, idx=i, img_path=li: self.get_image_url(futrue, idx, img_path))
tasks = [] for i, li in enumerate(self.images): if li.startswith("/"): # 本地图片 li = "." + li image_full_path = os.path.join(self.base_dir, li) if not os.path.exists(image_full_path): print(f"图片{image_full_path}不存在") continue task = asyncio.ensure_future(self.__upload_md_img(image_full_path)) # task.add_done_callback(lambda futrue: self.get_image_url(futrue, i, li)) task.add_done_callback(lambda futrue, idx=i, img_path=li: self.get_image_url(futrue, idx, img_path)) tasks.append(task) if len(tasks) == 0: return loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) loop.close() def get_image_url(self, t: asyncio.Task, idx, img_path): """回调,获取url""" img_url = t.result() print(f"{idx} {img_path}上传成功,url:{img_url}") self.net_images.append(img_url)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战