在 this question ,给出了如何删除只读文件的答案。它非常有效,但需要有未使用的参数。在 this other question有人询问如何在不添加特定注释的情况下告诉 pylint 未使用多个不相邻的参数(例如,通过使用 _
)。许多答案都是关于“天啊,你设计错了”,所以我保证我会举一个例子,在需要的地方,这是我无法控制的。这是那个例子。
shutil.rmtree(self._temp_dir, onerror=del_rw)
def del_rw(action, name, exc):
os.chmod(name, stat.S_IWRITE)
os.remove(name)
让 pylint 不会提示 action
和 exc
的“答案”是
shutil.rmtree(self._temp_dir, onerror=del_rw)
def del_rw(_action, name, _exc):
os.chmod(name, stat.S_IWRITE)
os.remove(name)
但新问题是,如何在没有 _action
或 _exc
作为参数的情况下执行此操作?
最佳答案
正如评论中所讨论的,您不能只忽略 action
和 exc
因为 rmtree
会将这些参数传递给回调。来自 python docs :
If
onerror
is provided, it must be a callable that accepts three parameters:function
,path
, andexcinfo
.
话虽如此,您有几个选择:
您可以在回调函数中添加
cb_
前缀(另请参阅 pylint docs),将您的函数变成:shutil.rmtree(self._temp_dir, onerror=cb_del_rw) def cb_del_rw(action, name, exc): os.chmod(name, stat.S_IWRITE) os.remove(name)
您可以使用keyword arguments (您也可以使用
*args
,但我发现这种方法更具可读性):shutil.rmtree(self._temp_dir, onerror=del_rw) def del_rw(**kwargs): name = kwargs['name'] os.chmod(name, stat.S_IWRITE) os.remove(name)
关于python - 如何删除shutil.rmtree中未使用的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47316154/