如何从python中的**kwargs参数中排除可选参数? 代码:检查警告:

问题描述

如果我使用可选参数输入来调用 subprocess.Popen(command,**kwargs),当我 .communicate() 返回并想要 .decode('utf8') 输出时,我会在 PyCharm 中遇到一个有趣的检查警告。>

代码

def my_call(command,**kwargs):
    process = subprocess.Popen(command,**kwargs)
    out,err = process.communicate()
    return out.decode('utf8'),err.decode('utf8') if err else err  # err Could be None

检查警告:

Unresolved attribute reference 'decode' for class 'str'

解决方法”:

由于 .communicate()输出是字节串 (as described here),因此如果不使用 encoding 作为可选参数调用函数,那么它不应该是运行时问题。尽管如此,我对此并不满意,因为将来可能会发生这种情况并导致 AttributeError: 'str' object has no attribute 'decode'

直接的答案是围绕解码参数进行 if-case 或 try-catch-operation,如下所示:

if 'encoding' in kwargs.keys():
    return out,err
else:
    return out.decode('utf8'),err.decode('utf8') if err else err

或者:

try:
    return out.decode('utf8'),err.decode('utf8') if err else err
catch AttributeError:
    return out,err

但是我不会以这种方式消除检查警告。

那么如何从 **kwargs 参数中排除一个可选参数以摆脱检查警告?

忽略未解决的参考问题不是一种选择。 我曾尝试将编码参数设置为认无:subprocess.Popen(command,encoding=None,**kwargs),但没有用。

解决方法

Python 中的返回类型是硬编码的,不依赖于提供给函数的输入参数(至少据我所知)。因此,将输入参数更改为 subprocess.Popen(command,encoding=None,**kwargs) 不会对函数的预期返回类型产生任何影响。为了摆脱警告,我的建议是将输入与 try-catch 块结合使用:

def my_call(command,**kwargs):
    process = subprocess.Popen(command,**kwargs)
    err: bytes
    out: bytes 
    out,err = process.communicate()
    try:
        return out.decode('utf8'),err.decode('utf8') if err else err
    catch AttributeError:
        # Optionally throw/log a warning here
        return out,err

或者,您可以使用将 if 条件与 isinstance(err,bytes) and isinstance(out,bytes) 结合使用的版本,这也可能会解决警告并且不会抛出错误,但在 Python 中您请求宽恕而不是获得许可EAFP