[Python-Dev] The `for y in [x]` idiom in comprehensions
Stephen J. Turnbull
turnbull.stephen.fw at u.tsukuba.ac.jp
Fri Feb 23 23:41:28 EST 2018
Chris Barker writes:
> But I still think the original:
>
> [g(y) for x in range(5) for y in [f(x)]]
>
> Is always going to be confusing to read.
But the point I was making with "def f(x=[0]):" was this: you have a
situation where your desired semantics is "value of some type"[1], but
the language's syntax doesn't permit a value of that type there, while
"singleton sequence of that type" works fine.
In fact, "singleton as value" is baked into Python in the form of
str.__getitem__ and bytes.__getitem__. So we now have four use cases
for singleton as value: two stringish actual types, and the two idioms
"mutable default argument" and "local variable in comprehension". The
horse is long since out of the barn.
Steve
Footnotes:
[1] Both "value" and "type" are used rather loosely here.
More information about the Python-Dev
mailing list