Using an anonymous function in Python

anonymous-function, python

Solution

You can use `lambda`, but it's usually a better idea to make a separate function and pass it.

self.Scraper.GetSubUrls(url, lambda url: self.UI.addLink(url[0], url[1]))

or

def addLink(url):
    self.UI.addLink(url[0], url[1])

self.Scraper.GetSubUrls(url, addLink)

Problem

I've got some code which downloads a list of data from numerous URLs, then calls another function, passing in each result. Something like... ``` def ShowUrls(self, url): Urls = self.Scraper.GetSubUrls(url) for Url in Urls: self.UI.addLink( Url[0], Url[1]) ``` This works fine but there's a long delay while `self.Scraper.GetSubUrls` runs, then all the UI calls are made very rapidly. This causes the UI to show "0 Urls added" for a long time, then complete. What I'd like is to be able to pass the `self.UI.addlink` method in to the `self.Scraper.GetSubUrls` method so that it can be called as soon as each URL is retrieved. This should make the UI show the correct count as soon as each url is retrieved. Is this possible? If so, what's the correct syntax? If I were in Javascript, I'd do something like.... ``` getSubUrls(url, function(x, y) {UI.addLink(x, y)}) ``` and then, inside getSubUrls do ``` SomeParamMethod(Pram1, Param2) ``` Is this possible? If so, what's the correct syntax?

Original source