my favorite line of py code so far

Peter Cacioppi peter.cacioppi at gmail.com
Sun Nov 10 03:57:22 EST 2013


Chris said :

"I think map is fine if you can use a named function, but if you can't
come up with a descriptive name for what you're doing, a comprehension
is probably better (as it'll have the code right there). Mapping _
across everything tells you nothing about what it's actually doing"

OK, this makes a lot of sense. (Any my apologies to Peter Otten if my previous post was overly snarky).

How about this? I put the following in my catchall_utility.py module

  # the oneArg combinator takes a multi-argument calleable
  # and returns the equivalent single argument calleable
  oneArg = lambda c: lambda x : c(*x)


With example code

  map(oneArg(P), zip([1,2,3], [6, 5, 4]))

To my mind the idea that oneArg(P) is a calleble that behaves exactly like P, with the only difference being oneArg(P) accepts P's arguments packed into a single iterable, is very intuitive.

I actually find the oneArg version more readable than the comprehension that unpacks explicitly using *. At this point I probably have equal experience coding Lisp and Py, with the latter more recent, so I don't think this bias can be chalked up to "experienced functional programmer, beginner py programmer".

To be clear, I was never really intending to keep the

  _ = lambda c : lambda x : c(*x)
  map(oneArg(P), zip([1,2,3], [6, 5, 4]))

code snippets in my final work product. The purpose of this thread was too fish around for ideas on what to replace it with when I execute the "use the unit tests to facilitate refactoring for better names and more professional idioms" step.

(We never, ever, skip that step, right?)

Although it is unlikely you will convince me to use the comprehension in this sort of situation, it's possible someone could convince me to use starmap with P instead of map with oneArg(P). Those two techniques are fully equivalent. But, to my mind, the latter just feels right, and I find that I write fewer bugs when I use idioms that resonate.

Thanks again, good thread for me



More information about the Python-list mailing list