Comment by vishnudeva

Comment by vishnudeva 3 days ago

18 replies

I think my answer: I have no idea what multi-line lambdas are, probably explains why I find Reflex (or Rio/Streamlit, etc) amazing, haha

For a person with zero front-end knowledge, it's a game changer.

greener_grass 3 days ago

In JavaScript you can do this:

    const f = (x, y) => {
      const z = x + y;
      const w = z * 2;
      return z - w + x;
    };
In Python, you cannot do this:

    f = (
      lambda x, y:
        z = x + y;
        w = z * 2;
        return z - w + x;
    )
Instead, you need to pull it out into a def:

    def f(x, y):
      z = x + y;
      w = z * 2;
      return z - w + x;
Sometimes, this is no big deal. But other times, it's damn annoying; the language forces you to lay out your code in a less intuitive way for no obvious benefit.
  • skeledrew 3 days ago

    Actually you can. If you really want a multi-line lambda with your example...

    ```f = lambda x, y: [ z := x + y, w := z 2, z - w + x, ][-1]```

    * That version does look strange, as it uses a list in order to get that last calculation. But I often use lambdas to check results in parametrized tests, and they naturally spread to multiple lines without the list hack since they're chains of comparisons.

    • throwitaway1123 2 days ago

      Using a list combined with the walrus operator is a clever hack, but it's nice to not be limited to expressions. In JS you can define the equivalent of a multi-line lambda function with any number of statements (which is helpful when you're passing a function as a callback e.g. in a React hook).

      • skeledrew 2 days ago

        It may be nice in the moment, but there's usually regret a few weeks/months down the line when trying to read that code, or angst for the next developer. There isn't that much more effort to just create a normal def to hold that increase in complexity suggested by the need for multiple statements. That's why functions were invented in the first place.

    • greener_grass 2 days ago

      That's pretty janky - I don't think it would pass review in many places!

      • skeledrew 2 days ago

        Interesting. I see HN has mangled my code block onto 1 line and replaced a couple stars, but the fixup should be obvious...

        Yes, it is, it should, and that's exactly the point. It'd look janky even without the `[-1]`, and this is what the core devs are trying to protect against. Lambdas are anonymous functions meant only to be used in places where expressions are valid, such as function parameters and return values. There's even a linter warning if you assign one to a variable. All to help reduce the creation of janky-looking code, and that's a huge benefit for most developers.