python - 检查 **kwargs 中的值的更简单方法

标签 python keyword-argument protocol-buffers

我有一个项目,其中包含很多 protobuf 消息,其中一些 protobuf 甚至还包含其他消息,其中也包含很多参数。

因为涉及的参数太多,几乎我编写的每个函数都使用 **kwargs 而不是必需/可选参数,所以我的函数通常如下所示:

def set_multiple_params(**kwargs):
    header, smp_message = Writer.createMessage(SetMultipleParametersRequestMessage_pb2.SetMultipleParametersRequestMessage,
                                               TIMESTAMP)
    data = smp_message.multipleParametersData
    data.maxPrice = kwargs['maxPrice'] if 'maxPrice' in kwargs else 15.54
    data.minPrice = kwargs['minPrice'] if 'minPrice' in kwargs else 1.57
    ....

    # list goes here with around 30 more checks like this, and finally
    
    return Writer.serializeMessage(header, smp_message)

Writer 只是一个使用 createMessage 的小型库。函数将 PacketHeader 数据附加到消息中,而 serializeMessage只需调用 serializeToString方法,并返回元组。

我使用它的方式创建了一个数据字典,并将其传递到 **kwargs 中。 我的代码可以工作,目前对我来说没问题,但是当我必须为每个函数编写 50 个这样的检查时,这就很乏味了。

所以问题是除此之外是否还有其他方法可以检查 **kwargs 中的 key ,或者这是我的最佳解决方案?我知道我可以使用链式 if,但我想知道是否有更简单或更 Pythonic 的东西。

除了 bool 值之外,这两个键都没有相同的值。我已经使用any()函数可以让我免于编写这些部分的代码。

最佳答案

data.maxPrice = kwargs.get('maxPrice', 15.54)

关于python - 检查 **kwargs 中的值的更简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41105920/

相关文章:

c# - protobuf3 中的重复 Int32Value(可为空的 int 数组)

python - 使用 FlaskClient 在测试 Flask 应用程序上获取 'Authorization' header 时出现问题

python - 将wav转换为mp3时如何使用pysox指定比特率

inheritance - 如何将 : 1. ISerialized 与 Serializer.Merge/Serialize & 2. ProtoIninclude 与 RuntimeTypeModel.Default 一起使用?

Python 方法采用一个位置参数,但给出了两个

python - 在 Python 函数中使用 **kwargs

java - 如何在 Java 中将 MySQL unsigned int 转换为 Protocol Buffer uint32?

python - 如何在 python 中的多个请求中使用相同的 cookie?

python - 如何在 Heroku 上的特定目录 (/app/assets/chromedriver) 中安装 chromedriver?

python - 为什么不能在 __init__ 关键字参数中使用类变量?