Explaining get() method with **kwargs?

Tazz B picture Tazz B · Apr 22, 2018 · Viewed 12.6k times · Source

Trying to figure out how this code is working.

I understand that **kwargs returns a dictionary and the get() function searches the dict for a given key and returns a default value if not found. However in the code I don't understand is if the get() method is searching for example: "clock" or self.clock or both.

def update(self, *args, **kwargs):
    self.screen = kwargs.get("screen",self.screen)
    self.clock = kwargs.get("clock",self.clock)
    self.active = kwargs.get("active",self.active)

Here is an example call to this method:

debug.update(active = numActive)

From my understanding, the variable numActive is passed through the update method as active and then as **kwargs which is then searched for via the get() method. Couldn't I just remove the use of kwargs seeing as I know how many parameters are needed?

Any help with understanding is appreciated.

Answer

Danny picture Danny · Apr 22, 2018

The second parameter in the get method is the default value.

According to Python2.7's documentation:

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

Source: https://docs.python.org/2/library/stdtypes.html#dict.get

Explanation When you try to 'get' something from a dictionary, if the key is not found, or the value is None, it will return None.

BUT, if you provide the second parameter (which is the default), if and only if the key is not found, default value will be returned.

Example without defaults

For the following code:

some_dict = {
    "key_1": 1,
    "key_2": None,
}
print some_dict.get("key_1")
print some_dict.get("key_2")
print some_dict.get("key_3")

You will get the output:

1
None
None

Example with defaults

For the following code

some_dict = {
    "key_1": 1,
    "key_2": None,
}
print some_dict.get("key_1", 1)
print some_dict.get("key_2", 2)
print some_dict.get("key_3", 3)

You will get the output:

1
None
3

Looking at your code

I will explain your code in the comments:

def update(self, *args, **kwargs):
    # If the kwargs contain the key 'screen', the following get method will
    # return its value, or else it would remain whatever value was in 
    # self.screen's variable before
    self.screen = kwargs.get("screen",self.screen)


    # If the kwargs contain the key 'clock', the following get method will
    # return its value, or else it would remain whatever value was in 
    # self.clock's variable before
    self.clock = kwargs.get("clock",self.clock)

    # If the kwargs contain the key 'active', the following get method will
    # return its value, or else it would remain whatever value was in 
    # self.active's variable before
    self.active = kwargs.get("active",self.active)

Hope this helps. Cheers.