0

In nodeJS using lambda expressions you can create very clean callback code but defining and returning a function at the same time. Like so:

events.on("loaded", ()=>{
  let x=1;
  console.log("loaded!", x+2);
});

If I were to try to accomplish the same thing in python, I would need to define the function before using it in the callback:

def l():
  x=1
  print("loaded!", x+2)

events.on("loaded", l)

By my eye is is a lot harder to read.

My question is: is there a clean way of writing a multi-line function in python for callbacks that can be used in-line?

Note: I cannot use a lambda expressions as I need multi-line functions.

Please alert me if there is already an answer to this question that I wasn't able to find. I will happly remove this myself if that is the case.

Zock77
  • 951
  • 8
  • 26
  • 1
    Python does not have an expression that can define an arbitrary function, at least not without jumping through a bunch of hoops with `compile` that would be even less readable. – chepner Oct 21 '19 at 17:07
  • 1
    Different languages have different idioms to accomplish similar stuff. You won't get anywhere by trying to convert code directly. Take time to learn the best practices – JBernardo Oct 21 '19 at 17:09
  • Thanks guys. That answered my question. – Zock77 Oct 22 '19 at 14:49

0 Answers0