←back to thread

317 points est | 1 comments | | HN request time: 0.237s | 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. ehsankia ◴[] No.17456957[source]
Doesn't tree have a way of iterating over nodes matching an xpath?

tree.xpath(TARGET_XPATH) I beleive. Aa

Point is the comprehension is flawed to start with. If you need f(x) on both side, then f(x) should happen first, rather than doing it inside and assigning it. That requires a new user to know the if part (at the end) gets executed first, which is dirty.