Hacker News new | ask | show | jobs
by Symen 3225 days ago
But your lambda example would be more clear if collections functions supported chaining. You can add a small comment if you want to be explicit. This way the code reads linearly, you don't have to wonder why a "square" function and "is_even" function are defined before you see how they are used.

    # square even numbers
    range(11)
      .filter(lambda x: not x % 2)
      .map(lambda x: x ** 2)
However such a chaining API is not practical in python, because lambda syntax is voluntarily crippled to one expression only.
1 comments

Long method chains are impractical in Python because of the line continuation rules. That's orthogonal to the question of whether complex functions should be required to have names.
There are a few gotchas but you can do it. Mostly you need to put you multi-line chain call inside parentheses if it is not already inside a function call or data structure (similarly to generator expressions).

For example I often end up doing:

    something(
        "Template string {thing}"
        .format(thing=33)
    )
It's possible but rarely more concise or clear than just using variables.

    label = "Template string {thing}".format(thing=33)
    something(label)
I guess it is a matter of preference at some point.

Storing each step in variables has the advantage to be self-documenting and nicer when debugging. However in many cases I feel like wasting energy trying to find short and adequate variable names for each steps in a computation, especially when the steps are clear enough by themselves but difficult to describe in 1-2 short words.

You also need to keep the variable names in sync when refactoring, which may cause even more refactoring if the line gets too long with the new name.

IMO it makes sense to use both styles where they feel most adequate.