From 21c3caaba44fc13221ba63600262e6eb15cbe824 Mon Sep 17 00:00:00 2001 From: Egor Tensin Date: Fri, 12 Feb 2016 08:07:19 +0300 Subject: refactoring --- print_mutual_friends.py | 38 +++++++++++++++----------------------- 1 file changed, 15 insertions(+), 23 deletions(-) (limited to 'print_mutual_friends.py') diff --git a/print_mutual_friends.py b/print_mutual_friends.py index b3beb39..9de77cb 100644 --- a/print_mutual_friends.py +++ b/print_mutual_friends.py @@ -2,41 +2,33 @@ # This file is licensed under the terms of the MIT License. # See LICENSE.txt for details. -import api, sys +import sys -def users_get(user_ids): - response = api.users_get(user_ids=','.join(user_ids), - fields='screen_name') - if len(response) < len(user_ids): - raise RuntimeError('Couldn\'t find at least one of the users!') - return response +from api import * -def friends_get(user_id): - return api.friends_get(user_id=user_id) +def query_friends(api, user): + return api.friends_get(user.get_uid(), fields=User.Field.SCREEN_NAME) -def extract_screen_name_or_uid(user): - if 'screen_name' in user: - return user['screen_name'] - return 'id' + str(user['uid']) - -def format_friend(user): - return '{} {} ({})'.format( - user['last_name'], user['first_name'], - extract_screen_name_or_uid(user)) +def format_user(user): + if user.has_last_name(): + return '{} {} ({})'.format(user.get_last_name(), user.get_first_name(), user.get_screen_name()) + else: + return '{} ({})'.format(user.get_first_name(), user.get_screen_name()) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser( description='Learn who your ex and her new boyfriend are both friends with.') + parser.add_argument(metavar='UID', dest='user_ids', nargs='+', help='user IDs or "screen names"') args = parser.parse_args() - users = users_get(args.user_ids) - user_ids = map(lambda user: user['uid'], users) - friend_lists = map(frozenset, map(friends_get, user_ids)) + api = API(Language.EN) + users = api.users_get(args.user_ids, fields=User.Field.SCREEN_NAME) + + friend_lists = map(lambda user: frozenset(query_friends(api, user)), users) mutual_friends = frozenset.intersection(*friend_lists) if mutual_friends: - mutual_friends = users_get(list(map(str, mutual_friends))) for friend in mutual_friends: - print(format_friend(friend)) + print(format_user(friend)) -- cgit v1.2.3