-2

So I'm relatively new to Python and I'm having a tough time getting my head around kwargs, seems like a simple enough concept but every use of it I see online seem to be different. Am I using it right?

I've a function plot_performance(), which creates a simple scatter plot, and has an optional keyword 'save' which if set to True should save the plot as a PNG.

def plot_performance(list_in, **kwargs):

    '''

    '''

    for key in kwargs:
        if (key == 'save') and (kwargs[key] is True):
            plt.savefig('plot.png', bbox_inches='tight')

First time posting a question so forgive me if my question is too general or my formatting is off, thanks!

Jordan
  • 7
  • 1
  • 3
    Welcome to SO. Usually you use kwargs if you have the possibility of several possible keyword arguments, in your case a simple `def plot_performance(list_in, save=false):` would do the trick. This is a method parameter with a default value, if no value for the second parameter is given, it will be false. If it is given, it will be the given value. – Bernhard Dec 06 '18 at 14:15
  • See [this question](https://stackoverflow.com/questions/1415812/why-use-kwargs-in-python-what-are-some-real-world-advantages-over-using-named) for sample usage –  Dec 06 '18 at 14:16
  • 2
    No, this is not a good use. Not only is that pointless when you could just have `save=False` in the function definition, you also wouldn't iterate over a dict to find a key, you would look up the key directly. – Daniel Roseman Dec 06 '18 at 14:16
  • Yeah, if you have only one optional argument, no need to use kwargs. – trsvchn Dec 06 '18 at 14:16
  • As the above said, there is no need for kwargs here. However, an easier solution to avoid `for` loop would be `if key in kwargs and kwargs[key]:` – BoobyTrap Dec 06 '18 at 14:18

1 Answers1

1

If you know or expect save to be passed, specify it directly. You probably have a default value in mind, so as Bernhard mentions in a comment:

def plot_performance(list_in, save=False):
    if save:
        put.save_fig(...)

If you did use kwargs, use its get method.

def plot_performance(list_in, **kwargs):
    save = kwargs.get('save', False)
    if save:
        ...

However, kwargs is typically used when you need to accept arbitrary keyword arguments that you don't necessarily know or care about, in order to pass them on to another function. An example involving an overridden method:

class Child(Base):
    def foo(self, x, **kwargs):
        # do something with x
        # Pass any other keyword args on to another class's definition
        # of foo.
        super().foo(**kwargs)

More rarely, it can be used to accept arbitrary keyword arguments without having to define them ahead of time:

class Namespace:
    def __init__(self, **kwargs):
        self.values = dict()
        for kw in kwargs:
            self.values[kw] = kwargs[kw]
chepner
  • 497,756
  • 71
  • 530
  • 681