Hacker News new | ask | show | jobs
by JimDabell 1060 days ago
You wouldn’t really write it as you have in the second example though. The Pythonic way of writing something like this is to use list comprehensions or generator expressions, for example:

    min(some_op(item) for item in bar.baz() if some_filter(item)).foo()
Or decomposed a little for clarity:

    processed_items = (some_op(item) for item in bar.baz() if some_filter(item))
    min(processed_items).foo()
This is pretty readable – a natural language description of the first line is “do some_op for each item in bar.baz that matches some_filter”, which corresponds 1:1 with the code.
3 comments

This feels somehow even worse. I don’t think it’s more readable than Op’s example, but now it’s also weird to write.

The chaining example in OP’s first example is way better

both examples seem pretty contrived and I think this comes down just what language you are used to. Their other code seems very JS-y.

I work in both python & js. The python reads like natural language:

    Processed items is a set of some transformation of each item in bar.baz() where something is true for that item.
    then Foo the smallest in that list.
It reads like english.

JS-y stuff doesn't read like natural language, but I do think its more concise and fits the IDE function discovery workflow better.

Both models can be made into horrid messes or elegant solutions. Both are highly readable.

Now I like the python one because I find it natural to attach contextual "whys" or "because" comments to them.

    Processed items is a set of some transformation of each item in bar.baz() where something is true for that item.
    then Foo the smallest item.
    # because foo is a slow function and we don't want to foo every bar and baz
And if you have nested list comprehensions this totally stops making sense somehow.