←back to thread

317 points est | 1 comments | | HN request time: 0s | source
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 #
1. eesmith ◴[] No.17452781[source]
The best I could come up with involved some repetition, because of the double-comprehension boilerplate

  found_nodes = (node.find(SOME_XPATH) for node in tree)
  [found_node.get("value") for found_node in found_nodes
       if found_node is not None]
or as a one-liner:

  [found_node.get("value") for found_node in (
      node.find(SOME_XPATH) for node in tree) if found_node is not None]
It's 15 characters longer than your := version, at 110 characters instead of 95.