日常生活的交流与学习

首页 新随笔 联系 管理

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)
posted on 2024-01-21 12:37  lazycookie  阅读(9)  评论(0编辑  收藏  举报