data_garden data_garden - 1 month ago 7
Python Question

Python - unpacking kwargs in local function call

I would like to pass a

dictionary
:

items = {"artist": "Radiohead", "track": "Karma Police"}


as a parameter to this
function
:

def lastfm_similar_tracks(**kwargs):

result = last.get_track(kwargs)
st = dict(str(item[0]).split(" - ") for item in result.get_similar())
print (st)


where
last.get_track("Radiohead", "Karma Police")
is the correct way of calling the local
function
.

and then call it like this:

lastfm_similar_tracks(items)


I'm getting this error:

TypeError: lastfm_similar_tracks() takes exactly 0 arguments (1 given)


how should I correct this?

Answer

First problem: you need to pass items in like this:

lastfm_similar_tracks(**items)

Second problem, inside lastfm_similar_tracks, kwargs is a dictionary, in which the keys are of no particular order, therefore you cannot guarantee the order when passing into get_track. The best that you can do is:

result = last.get_track(kwargs['artist'], kwargs['track'])

At this point, the code should work the way you intended. However, I question the use of **kwargs in lastfm_similar_tracks: do you really need to define it that way? How about:

def lastfm_similar_tracks(artist, track, **kwargs):
    result = last.get_track(artist, track)
    # The rest of your code here

Then you can call it like so:

lastfm_similar_tracks(**items)

This way, you ensure that the caller must pass in artist and track or the function call will fail.