Search code examples
pythonkeyword-argumentprotocol-buffers

Easier way to check values in **kwargs


I have a project that contains a lot of protobuf messages, and some of these protobufs even include other messages that also have a lot of parameters within.

Because there are so many parameters involved, almost every function that I write uses **kwargs instead of required/optional arguments, so my functions usually look like this:

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 is just a small library that uses createMessage function to append the PacketHeader data to the message, while serializeMessage simply calls the serializeToString method, and returns the tuple.

I use this in the way that I create a dict of data which I pass into the **kwargs. My code works, and it's ok with me for now, but it's tedious when I have to write 50 checks like this per function.

So the question is if there is any other way to check the key in **kwargs other than this, or is this my best solution? I know I can use chained if's, but I was wondering if there is something easier or more Pythonic.

Neither of the keys have the identical values, except the booleans. I already use any() function to save myself from writing these parts of the code.


Solution

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