问题
In this question, an answer to how to remove read-only files is presented. It's super effective but requires having unused parameters. In this other question it was asked how to tell pylint that multiple non-adjacent parameters are unused without adding a specific comment (e.g., by using _
). Many of the answers were approximately "ZOMG YOU'RE DESIGNING IT WRONG" so I promised I would put up an example where this is needed and out of my control. Here is that example.
shutil.rmtree(self._temp_dir, onerror=del_rw)
def del_rw(action, name, exc):
os.chmod(name, stat.S_IWRITE)
os.remove(name)
The "answer" so that pylint would not complain about action
and exc
is to
shutil.rmtree(self._temp_dir, onerror=del_rw)
def del_rw(_action, name, _exc):
os.chmod(name, stat.S_IWRITE)
os.remove(name)
but the new question is, how to do this without having _action
or _exc
as parameters?
回答1:
As discussed in the comments, you cannot just ignore action
, and exc
because rmtree
will pass those arguments to the callback. From the python docs:
If
onerror
is provided, it must be a callable that accepts three parameters:function
,path
, andexcinfo
.
That being said, you have a couple of options:
You can prefix the callback with a
cb_
(see pylint docs on this as well), turning your function into: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)
You can use keyword arguments (you could also use
*args
, but I find this approach more readable):shutil.rmtree(self._temp_dir, onerror=del_rw) def del_rw(**kwargs): name = kwargs['name'] os.chmod(name, stat.S_IWRITE) os.remove(name)
来源:https://stackoverflow.com/questions/47316154/how-to-remove-unused-function-parameters-in-shutil-rmtree