data_garden data_garden - 1 year ago 70
Python Question

Python - unpacking kwargs in local function call

I would like to pass a


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

as a parameter to this

def lastfm_similar_tracks(**kwargs):

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

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

and then call it like this:


I'm getting this error:

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

how should I correct this?

Answer Source

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


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:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download