←back to thread

317 points est | 1 comments | | HN request time: 0.297s | 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 #
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 #
carapace ◴[] No.17451929[source]
How about:

    [n.get("value") for n in filter(None, (node.find(SOME_XPATH) for node in tree))]
Or just:

    F0 = lambda node: node.find(SOME_XPATH)
    F1 = lambda node: node.get("value")
    result = map(F1, filter(None, map(F0, tree)))
replies(2): >>17452550 #>>17478675 #
1. aleaxit ◴[] No.17478675[source]
As an aside, this usage of `lambda` is redundant with a normal `def` statement:

    def F0(node): return node.find(SOME_XPATH)
etc. If you're binding the new function to a name anyway, why bother with `lambda` when `def` works just fine?