1

I'm a complete noob who just started learning Python. I'm playing around with the pylast library for Last.fm to pull a list of a user's neighbours & some of their attributes, but when I try to print a neighbour's country, I get the following error:

thrillofme
None
0
Traceback (most recent call last):
  File "/Users/Moi/DSR/Week 2/My tutorials/my-lastfm-thing-3.py", line 24, in <module>
    print country
  File "/Library/Python/2.7/site-packages/pylast.py", line 944, in r
    return _string(funct(*args))
  File "/Library/Python/2.7/site-packages/pylast.py", line 3497, in _string
return text.encode("utf-8")
AttributeError: 'NoneType' object has no attribute 'encode'

Looking at some other solutions to this error message, I get the impression that country is not encoded correctly to print, but I can't quite figure out what to do about it. Any help would be greatly appreciated! Here's my code.

import pylast

api_key = "XXX"
username = "Strangelove"
network = pylast.LastFMNetwork(api_key = api_key)
user = pylast.User(username, network)

# Let's pull a list of the specified user's Last.fm neighbours.
# Neighbours are users with a similar taste in music.

neighbours = user.get_neighbours()

for i in neighbours:
    gender = i.get_gender()
    age = i.get_age()
    country = i.get_country()
    print i
    print gender
    print age
    print country
Daniel
  • 53
  • 6
  • It looks like the method for deciding what gets printed for an object (`__repr__`) is set up for the Neighbor objects in such a way that it assumes the various attributes are not `None`. Is it possible you're looking at Neighbors for this user and those Neighbors actually don't list their country? What does the country field report if the user does not fill it in? If it's `None` and the last.fm API doesn't handle this, you'll have to use `try: ... except:` or some other form of exception handling to avoid it. – ely Jan 30 '13 at 17:05

2 Answers2

2

The country name is missing, but the pylast library is not dealing with that case correctly. You'll have to test for the empty country case yourself:

if country.name:
    print country
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

I've fixed this in my fork of pylast.

When you call country = i.get_country(), it now returns None instead of a Country object where name is None.

Hugo
  • 27,885
  • 8
  • 82
  • 98