PYTHON: Set a default value if kwargs key is missing in parameters when function is being called

I'm trying to refactor my code by using kwargs. Lets say I have a callback function that hanldes 50 variables and sometimes I want to call that function and pass only 10 kwargs in parameter. Is it possible to have a default value like None when the KEY of that kwargs is missing in parameter?

This is a short example of what I want to achieve

class Obj:
    def __init__(self, first_name, last_name, middle_name):
        self.first_name = first_name
        self.last_name = last_name
        self.middle_name = middle_name

    def main(self):
        print(f"BEFORE: {self.last_name}, {self.first_name} {self.middle_name}")
            new_first_name = "Mark Anthony",
            new_last_name  = "Vale"
            # new_middle_name key => not using here

    def callback(self, **kwargs):
        self.first_name         = kwargs['new_first_name']
        self.last_name          = kwargs['new_last_name']

        # Set a default value if new_middle_name key is missing in parameters when self.callback is being called
        self.middle_name        = "Not Foo" if kwargs['new_middle_name'] else kwargs['new_middle_name']

        print(f"AFTER: {self.last_name}, {self.first_name} {self.middle_name}")

obj = Obj(first_name="John", last_name="Doe", middle_name="Foo")

This will throw KeyError: 'new_middle_name'

Read more here:

Content Attribution

This content was originally published by Mark Anthony Vale at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: