← Back to context

Comment by ashdev

4 days ago

Disagree.

In the first instance, the original code is readable and tells me exactly what's what. In your example, you're sacrificing readability for being clever.

Clear code(even if verbose) is better than being clever.

Using a very common utility in the standard library is to avoid reinventing the wheel is not "clean code"?

defaultdict is ubiquitous in modern python, and is far from a complicated concept to grasp.

  • I don't think that's the right metaphor to use here, it exists at a different level than what I would consider "reinventing the wheel". That to me is more some attempt to make a novel outward-facing facet of the program when there's not much reason to do so. For example, reimplementing shared memory using a custom kernel driver as your IPC mechanism, despite it not doing anything that shared memory doesn't already do.

    The difference between the examples is so trivial I'm not really sure why the parent comment felt compelled to complain.

Imo, if you read such code the first time, you may prefer the first. If you read it for the 20th time, you may prefer the second. Once you understand what you are doing, often one prefers more concise syntax that helps in handling complexity within a larger project. But it can seem a bit "too clever" in the beginning.

  • This happened to me with comprehensions in python, and with JS' love for anonymous/arrow functions.

    Once you get used to a language's "quirks" (so long as they're considered idiomatic), they no longer feel quirky, and it's usually pretty quick.

    • You get to the same point with non-considered idiomatic syntax also, the only problem being that it will be only you who understands it.

      1 reply →

I think code clarity is subjective. I find the second easier to read because I have to look at less code. When I read code, I instinctively take it apart and see how it fits together, so I have no problem with the second approach. Whereas the first approach is twice as long so it takes me roughly twice as long to read.

Interesting! Thanks for the responses. I'm not python native and haven't worked as extensively with python as some of you here.

That said, I'll change my mind here and agree on using std library, but I'd still have separate 'key' assignment here for more clarity.

I would keep the explicit key= assignment since it's more than just a single literal but otherwise the second version is more idiomatic and readable.