如何删除shutil.rmtree中未使用的函数参数 [英] How to remove unused function parameters in shutil.rmtree

查看:101
本文介绍了如何删除shutil.rmtree中未使用的函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题中,回答如何删除只读文件被呈现.它非常有效,但需要使用未使用的参数.在另一个问题中,有人问如何告诉pylint在不添加特定注释的情况下(例如,通过使用 _),未使用多个不相邻的参数.许多答案都大致是ZOMG 你设计错了",所以我保证我会举一个例子,在需要的地方,这是我无法控制的.这是那个例子.

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)

使 pylint 不会抱怨 actionexc 的答案"是

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)

但新的问题是,如何在没有 _action_exc 作为参数的情况下做到这一点?

but the new question is, how to do this without having _action or _exc as parameters?

推荐答案

正如评论中所讨论的,你不能忽略 actionexc 因为 rmtree 将这些参数传递给回调.来自 python 文档:

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:

如果提供了onerror,它必须是一个可调用的,接受三个参数:functionpathexcinfo.

If onerror is provided, it must be a callable that accepts three parameters: function, path, and excinfo.

话虽如此,您有几个选择:

That being said, you have a couple of options:

  • 您可以使用 cb_ 为回调添加前缀(请参阅 pylint 文档 在这方面),把你的功能变成:

  • 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)

  • 您可以使用关键字参数(您也可以使用 *args,但我发现这种方法更具可读性):

  • 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)
    

  • 这篇关于如何删除shutil.rmtree中未使用的函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆