The principle of duck typing says that you shouldn't care what type of object you have - just whether or not you can do the required action with your object. For this reason the
isinstance
keyword is frowned upon. - -Definition
In below snippet(function) group_tweets_by_state
, following definition of duck typing, action setdefault
is performed on the object tweets_by_state
by appending object tweet
def group_tweets_by_state(tweets):
tweets_by_state = {}
USA_states_center_position = {n: find_center(s) for n, s in us_states.items()}
for tweet in tweets: # tweets are list of dictionaries
if hassattr(tweet, 'setdefault'): # tweet is a dictionary
state_name_key = find_closest_state(tweet, USA_states_center_position)
tweets_by_state.setdefault(state_name_key, []).append(tweet)
return tweets_by_state
My understanding is, function hasattr(tweet, 'setdefault')
is type checking tweet
to be of <class 'dict'>
type in duck typing style, before append.
Is my understanding correct? Does function group_tweets_by_state
follow duck typing?