[Python-ideas] 'where' statement in Python?
Chris Rebert
pyideas at rebertia.com
Thu Jul 22 06:34:02 CEST 2010
On Wed, Jul 21, 2010 at 9:07 PM, Carl M. Johnson
<cmjohnson.mailinglist at gmail.com> wrote:
> There have been questions about whether there are any cases of the
> given/where/let/whatever solving problems that would otherwise be
> cumbersome to solve. I think it could help get around certain for-loop
> gotchas:
>
>>>> funcs = []
>>>> for i in range(5):
> ... def f():
> ... print("#", i)
> ... funcs.append(f)
> ...
>>>> [func() for func in funcs]
> # 4
> # 4
> # 4
> # 4
> # 4
> [None, None, None, None, None]
>
> D’oh! (This can be a real world problem if you have a list of methods
> you want to decorate inside a class.)
>
> One current workaround:
>
>>>> funcs = []
>>>> for i in range(5):
> ... def _():
> ... n = i
> ... def f():
> ... print("#", n)
> ... funcs.append(f)
> ... _()
> ...
>>>> [func() for func in funcs]
> # 0
> # 1
> # 2
> # 3
> # 4
> [None, None, None, None, None]
>
> Not pretty, but it works.
>
> In let format (I’m leaning toward the format “let [VAR = | return |
> yield] EXPRESSION where: BLOCK”):
>
> funcs = []
> for i in range(5):
> let funcs.append(f) where:
> n = i
> def f():
> print("#", n)
>
> [func() for func in funcs]
>
> Still a little awkward, but not as bad, IMHO.
Neither of those seem (imo) better than the other current workaround:
funcs = []
for i in range(5):
def f(i=i):
print("#", i)
funcs.append(f)
They're all non-obvious idioms, but at least this one is short and
easily recognized.
Cheers,
Chris
More information about the Python-ideas
mailing list