Keep one thing in mind, Python is NOT asynchronous as Node.js is. But both of them have first order functions. That means, you can create new functions dynamically, pass them as arguments, return them from other functions, store them in variables.
The important thing to be noted is, the dynamic function creation mechanism in python is achieved by lambda
keyword and those functions are called lambda functions. The lambda functions are very restrictive. They can only contain only one expression, not even a single statement. Consider this example,
fs.readFile("filename", function(err, content) {
if (err) {
console.error(err);
} else {
console.log(content.toString());
}
});
As you can see, we have defined a function inline and that will be used only once when the readFile
call finishes reading the file. You cannot define such functions in python instead, you can create a function which does whatever has to be done and then pass the function name as a parameter.
Performance wise, I really don't think I can compare them but lets say we are executing the above seen readFile
function in a loop. In javascript, the inline function has to be created multiple times, to be passed to the readFile
but in python, since that is not an option, we don't have to create new function every time, we can define once and use it always. That's why lambda
s are bit slower in python, because they have to created when the statement is executed. You can see this with this example
from timeit import timeit
print timeit('sorted(["abcd", "abc", "ab", "a"], key=lambda x:len(x))')
print timeit('sorted(["abcd", "abc", "ab", "a"], key=len)')
In the first version, we are creating a new lambda function and that gives us the length of each and every element in the respective iterations. In the second version, we are using the built in function len
directly. And when I executed this piece of code on my machine, I got
1.33205795288
0.976922988892
So, using already defined functions are better than creating one with lambdas.