←back to thread

317 points est | 7 comments | | HN request time: 0.447s | source | bottom
Show context
passive ◴[] No.17450989[source]
This is nice.

I very frequently use something like the following:

    [node.find(SOME_XPATH).get("value") for node in tree if node.find(SOME_XPATH) is not None]
Which I can soon rewrite as:

    [found_node.get("value") for node in tree if (found_node := node.find(SOME_XPATH)) is not None]
There's a certain amount of complexity introduced, but I think removing the duplication makes up for it. This is one of the few remaining cases in Python where I feel like there's not a simple way to avoid repeating myself.
replies(3): >>17451275 #>>17452781 #>>17456957 #
stared ◴[] No.17451275[source]
Still fail to see why instead of that there isn't more functional list comprehension, with maps and filters. That way we wouldn't get such problems in the first place.

For more advanced list compherensions, even JavaScript (ES6+) is more readable.

replies(2): >>17451517 #>>17451929 #
1. joeframbach ◴[] No.17451517[source]
[found_node.get("value") for node in tree if (found_node := node.find(SOME_XPATH)) is not None]

tree.map(node => node.find(SOME_XPATH)).filter(Boolean).map(node => node.get("value"))

I can deal with either language at this level of complexity. Anything more complicated needs more LoC in either language.

replies(2): >>17453332 #>>17453415 #
2. williamdclt ◴[] No.17453332[source]
I vastly prefer the second one, as I would expect to see it written something like this:

  tree
    .map(node => node.find(SOME_XPATH))
    .filter(Boolean)
    .map(node => node.get("value"))
I don't use Python on a daily basis, but I find that infinitely more readable than the comprehension version (plus, it's a syntax used in several major languages)
replies(1): >>17453797 #
3. hellofunk ◴[] No.17453415[source]
What is "node => ", is that valid Python? I'm new to the language and have never seen the => syntax before. The docs for 'map' don't show it either.
replies(3): >>17453649 #>>17453724 #>>17453839 #
4. vthriller ◴[] No.17453649[source]
It's not Python, the second is actually a counterexample in JavaScript, where `node =>` is similar to Python's `lambda node:`
5. ◴[] No.17453724[source]
6. lukeschlather ◴[] No.17453797[source]
In fairness, the Python also should be broken up. It should be:

    [
      found_node.get("value") 
      for node in tree 
      if (found_node := node.find(SOME_XPATH)) is not None
    ]
I think I also prefer Ruby/Javascript style comprehensions, but it's worth comparing well formatted code.
7. ◴[] No.17453839[source]