How to make Self-Invoking Anonymous Functions in Python?
For example with JavaScript:
Standard way:
function fn (a) {
if (a == 1) {
alert(a);
}
else {
alert(0);
}
/...
}
fn(1);
Self-Invoking Anonymous call:
!function(a) {
if (a == 1) {
alert(a);
}
else {
alert(0);
}
/...
}(1);
Are there any analogues in Python?
I don’t think is possible, given your comments to the lambda answers. The
lambdaoperator is Python’s only way of supporting anonymous functions. If you need to support statements, then you need to use adef, which always must be named.Keep in mind that lambdas can support limited if-then logic, however. The following two are
lambdaexpressions that implements the if-then logic given above:More literally: