May 13

See Which Twitterers Don’t Follow You Back In 15 Lines of Python

Using Python to display which Twitter users you follow don't follow you back.

Today, I came across a Ruby script that Jerod Santo blogged about yesterday: See Which Twitterers Don’t Follow You Back In Less Than 15 Lines of Ruby. I quickly felt the need to implement the same in Python to see how much code it would take.

I used the awesome Minimalist Twitter API for Python, which I have used and blogged about before. After a couple refactorings, I ended up with 15 lines:

from twitter.api import Twitter

USERNAME = 'r1cky' # set to your/any username

twitter = Twitter() # username/password not required for these calls
friends = twitter.friends.ids(screen_name=USERNAME)
followers = twitter.followers.ids(screen_name=USERNAME)
guilty = [x for x in friends if x not in followers]

print "There are %s tweeps you follow who do not follow you" % len(guilty)

for user_id in guilty:
    user = twitter.users.show(user_id=user_id)
    print "%s follows %s and has %s followers." % \
              (user['name'], user['friends_count'], user['followers_count'] )

It does seem like more code than the Ruby version. I especially like how you can subtract one array from the another in Ruby:

guilty = base.friend_ids - base.follower_ids

I am not sure that this can be made as elegant in Python... Can it?

To make the code re-usable, I created a function that takes a username and returns the users that don't follow back:

from twitter.api import Twitter

def no_follow_back(username):
    twitter = Twitter()   # username/password not required for these calls
    friends = twitter.friends.ids(screen_name=username)
    followers = twitter.followers.ids(screen_name=username)

    def get_user_by_id(user_id):
        return twitter.users.show(user_id=user_id)

    return [get_user_by_id(x) for x in friends if x not in followers]

A usage example (I saved the function above in a file called twitfun.py):

>>> from twitfun import no_follow_back
>>> guilty = no_follow_back('papajuans')
>>> len(guilty)
16
>>> guilty[0]["screen_name"]
u'shanselman'

Powered by my hackings on Django-Mingus a Django project, PostgreSQL, memcached, nginx, Apache + mod_wsgi, Ubuntu, Rackspace Cloud,...

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

html5 | top