
On Mon, Jan 25, 2016 at 5:22 PM Steven D'Aprano <steve@pearwood.info> wrote:
# Still a toy, but perhaps a bit more of a realistic toy. searchers = [] for provider in search_provider: key = API_KEYS[provider] url = SEARCH_URLS[provider] def lookup(*terms): terms = "/q=" + "+".join(escape(t) for t in terms) u = url + ("key=%s" % key) + terms return fetch(u) or [] searchers.append(lookup)
I'd define the basic function outside the loop. def lookup(root_url, api_key, *terms): args = root_url, api_key, "+".join(escape(t) for t in terms) url = '%s?key=%s&q=%s' % args return fetch(url) or [] Then use ``functools.partial`` inside the loop to create the closure. searchers = [] for provider in search_provider: key = API_KEYS[provider] url = SEARCH_URLS[provider] searchers.append(partial(lookup, url, key)) Or even more concisely, you could use a comprehension at that point. searchers = [partial(lookup, SEARCH_URLS[p], API_KEYS[p]) for p in search_provider]