I watched Raymond Hettinger's Idiomatic Python talk, and learned about the sentinel argument to iter()
.
I'd like to try to apply it to a piece of code I'm working on iterating over an API that uses pagination (it's Twilio, but not relevant to my question).
I have an API that returns: a list of data, and a next page URL. When the pagination is exhausted, the next page URL returns as an empty string. I wrote the fetching function as a generator and looks roughly like this:
def fetch(url):
while url:
data = requests.get(url).json()
url = data['next_page_uri']
for row in data[resource]:
yield row
This code works fine, but I'd like to try to remove the while
loop and replace it with a call to iter()
using the next_page_uri
value as the sentinel argument.
Alternately, could this be written with a yield from
?