def get_user_timeline(screen_name, count=200):
"""Return list of most recent tweets posted by screen_name."""

    # ensure count is valid
    if count < 1 or count > 200:
        raise RuntimeError("invalid count")

    # ensure environment variables are set
    if not os.environ.get("API_KEY"):
        raise RuntimeError("API_KEY not set")
    if not os.environ.get("API_SECRET"):
        raise RuntimeError("API_SECRET not set")

    # get screen_name's most recent tweets
    # https://dev.twitter.com/rest/reference/get/users/lookup
    # https://dev.twitter.com/rest/reference/get/statuses/user_timeline
    # https://github.com/ryanmcgrath/twython/blob/master/twython/endpoints.py
        twitter = Twython(os.environ.get("API_KEY"), os.environ.get("API_SECRET"))
        user = twitter.lookup_user(screen_name=screen_name)
        if user[0]["protected"]:
            return None
        tweets = twitter.get_user_timeline(screen_name=screen_name, count=count)
        return [html.unescape(tweet["text"].replace("\n", " ")) for tweet in tweets]
    except TwythonAuthError:
        raise RuntimeError("invalid API_KEY and/or API_SECRET") from None
    except TwythonRateLimitError:
        raise RuntimeError("you've hit a rate limit") from None
    except TwythonError:
        return None

This is the function that returns the recent tweets of the screen name given in the argument. What don't understand is what it returns. return [html.unescape(tweet["text"].replace("\n", " ")) for tweet in tweets] Why do the square brackets exist? and what does tweet["text"] mean in there?


The [expression_using_X for X in Y] is evaluating expression_using_X for every X being an element of Y, and the [] make that list of expression values a Python list.

squares = [x**2 for x in range(11)]

would for example create a list of square numbers, from 0 to 100.

tweet["text"] indicates that tweet (an element of tweets) is a dict, and has a property "text", tweet["text"] will evaluate to that property's value.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .