Thursday, January 16, 2014

Python **kwargs appear immutable in method

This is an interesting one.

You can pass an arbitrary number of keyword arguments to a method in Python using **kwargs.
This is a dictionary and you can iterate over items(), keys() and values() and do all the usual dict stuff.
However if you say, delete an item from the dictionary from within a method it does not change the dict that was passed in.

Example with ordinary dict.


def filter_args(kwargs):
    for k, v in kwargs.items():
        if v > 10:
            del kwargs[k]

args = {"a":12, "b":2}
filter_args(args)
print args


This prints the following

{'b': 2}



Now an example with **


def filter_args(**kwargs):
    for k, v in kwargs.items():
        if v > 10:
            del kwargs[k]
args = {"a":12, "b":2}
filter_args(**args)
print args


This prints

{'a': 12, 'b': 2}



It only changed the dict inside the method.




1 comment:

  1. Very nice blog, thanks for this post and I have some special things for you. If you are finding something to relax, disney junior games online; free disney games for kids will be my best recommendation for you. Let’s play and get more deep relaxation!
    Beside, you can try Kirigami. Now, you can completely play this addicting fun game on your mobile. Have fun!!!!

    ReplyDelete