Search code examples
pythonreserved-wordslast.fm

Python reserved keyword as argument does not work (although it should?)


This code

def get_recent_tracks(username, fromuts):
    print(fromuts)
    recent_tracks = lastfm_network.get_user(username).get_recent_tracks(**{'from':fromuts})
    for i, track in enumerate(recent_tracks):
        printable = track_only(track)
        print(str(i + 1) + " " + printable)
    return recent_tracks

results in

get_recent_tracks() got an unexpected keyword argument 'from'

The print() function returns the correct result. I learned several programming languages in my youth. Unfortunately, my youth being some 30 years ago, Python was not one of them. What I need is a working equivalent of

recent_tracks = lastfm_network.get_user(username).get_recent_tracks(from=fromuts)

For other params like limit=20 the code works just fine.


Solution

  • There's nothing strictly wrong with the format of your code. That code will get around the problem of from being a Python keyword, and it is doing so. So you've gotten past that problem. The problem now is more fundamental and has nothing to do with the fact that from is a keyword...

    The problem is simply that the get_recent_tracks method does not accept a named parameter with the name from. You'd expect this, because it would be hard for it to define such a parameter, and it wouldn't make sense for it to do so knowing that calling it with such a named parameter would be problematic. Read the docs for the method and supply it with the correct parameters, and you won't have an issue.

    UPDATE: Collecting information from comments, the issue seems to be that the OP was assuming a one-to-one mapping between the names and existence of each of the parameters to the HTTP API call that underlies the get_recent_tracks Python method. Here are the docs for each of these APIs:

    Python: https://hexdocs.pm/elixirfm/0.1.2/Elixirfm.User.html#get_recent_tracks/2

    HTTP: https://last.fm/api/show/user.getRecentTracks

    According to @Dierk, the OP, the equivalent parameter exists in the Python API and has the name time_from. This isn't reflected in the documentation referenced above. I notice that in that same documentation, there is the comment "start and end times not implemented yet" for another method in the API. So maybe this documentation is outdated, and support for the "time" parameters has since been added to the API.