Remix.run Logo
davepeck 9 days ago

We wanted at least a couple examples that showed use of Python's newer pattern matching capabilities with the new Interpolation type. From this outsider's perspective, I'd say that developer instincts and aesthetic preferences are decidedly mixed here -- even amongst the core team! You can certainly write this as:

    def f(template: Template) -> str:
        return "".join(
            item if isinstance(item, str) else
            format(convert(item.value, item.conversion), item.format_spec)
            for item in template
        )
Or, y'know, several other ways that might feel more idiomatic depending on where you're coming from.
pansa2 9 days ago | parent [-]

Your example is interesting - `join`, a generator expression and a ternary, and Python requires us to write all of them inside-out. It's a shame we can't write that in a more natural order, something like:

    def f(template):
        return (for item in template:
            isinstance(item, str) then item else
            format(convert(item.value, item.conversion), item.format_spec)
        ).join('')
davepeck 9 days ago | parent [-]

Yeah. `join` has forever been backwards to me in Python and I still sometimes get it wrong the first time out.

Comprehensions, though -- they are perfection. :-)

pansa2 9 days ago | parent [-]

IMO comprehensions like `[x**2 for x in range(4)]` would be better written as `[for x in range(4): x**2]`.

That would make the mapping between a comprehension and the equivalent loop much clearer, especially once you use nested loops and/or conditionals.

For example, to flatten a list of lists `l = [[1, 2], [3], [4, 5, 6]]`:

    [item for sublist in l for item in sublist]
vs

    [for sublist in l: for item in sublist: item]
zahlman 8 days ago | parent | next [-]

I think it's very deliberate that these sorts of expressions are inside-out from the corresponding statements. It mixes and matches modes of thinking in my mind - the same kind of mistake as command-query separation violations. When I read a list comprehension, I can read it left to right: "A list (`[`) of each `item` that I get, if I look `for` each `sublist` that is `in l`, then `for` each `item` which is `in` that `sublist`." And the entire description is - well - descriptive, not imperative. With the other order, I have to think in terms of explicitly following the steps, and then mentally translating the last `item` into an imperative "... and put it into the result list".

Hackbraten 8 days ago | parent | prev [-]

That would make dict comprehensions confusing due to two occurrences of colons with different semantics.

pansa2 8 days ago | parent [-]

Ah, yes - good point!