user7345804
user7345804

Reputation:

How can one use dictionary kwargs as callable function parameters?

I am trying to learn how to use kwargs via dictionaries as function inputs. As a simple example to learn from, I am trying to make a basic (x,y) plot for which the kwargs can specify the color of the curve and some other plot specs.

import numpy as np
import matplotlib.pyplot as plt

## generate data
f = lambda x : np.array([xi**2 for xi in x]) # function f(x)
x = np.linspace(0, 100)
y = f(x)

## define plotting routine
def get_plot(x, y, kwargs):
    """
    This plot will take multiple kwargs when successful.
    """
    plt.plot(x, y, **kwargs)
    plt.show()

I first try to generate the plot using one kwarg. This works.

plot_dict = dict(color='red')
get_plot(x, y, plot_dict)
>> plot appears 

I then try to generate the plot using two kwargs. This doesn't work.

plot_dict = dict(color='red', xlabel='this is the x-axis')
get_plot(x, y, plot_dict)
>> AttributeError: Unknown property xlabel

But I was under the impression that xlabel is a kwarg because it is a callable arg like color. What is the source of my misunderstanding/mistake?

Upvotes: 0

Views: 624

Answers (1)

Mohamed Ali JAMAOUI
Mohamed Ali JAMAOUI

Reputation: 14689

Change to this:

def get_plot(x, y, **kwargs):
    """
    This plot will take multiple kwargs when successful.
    """
    plt.plot(x, y, **kwargs)
    plt.show()

and call the function like this: get_plot(x, y, **plot_dict).

Check this tutorial to understand how to use **kwargs.

In nutshell, what **kwargs does, is explode the dictionary into pairs of argument=value, i.e, kwarg1=val1, kwarg2=val2.. instead of you doing that manually.

Upvotes: 3

Related Questions