Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an anonymous function in Python

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?

like image 742
Basic Avatar asked Nov 18 '12 00:11

Basic


People also ask

How do you declare an anonymous function in Python?

These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions. Lambda forms can take any number of arguments but return just one value in the form of an expression.

What is the scope of anonymous function without lambda in Python?

Python Anonymous functions are defined using the keyword ‘ lambda ‘, so technically there is no scope for anonymous function without lambda. But there are instances that say that it can be done using constructors. Constructors initiate the object of a class and are defined using keyword __init__ .

How do you use anonymous map in Python?

Anonymous function using map in Python Map function is used to simplify the program. It takes function followed by iterations as an argument. Map is one of the functions widely used by advanced programmers as it facilitates to implement of the function on each iteration individually.

What is an anonymous function in C++?

The act of defining a function using the def keyword binds that function to a name. However, some functions can be defined without giving them a name. Such functions are called “anonymous” and are defined using the lambda keyword. The following two definitions are equivalent.


1 Answers

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)
like image 128
Ry- Avatar answered Oct 21 '22 18:10

Ry-