[Python-ideas] 'where' statement in Python?

Carl M. Johnson cmjohnson.mailinglist at gmail.com
Thu Jul 22 06:07:19 CEST 2010


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.

-- Carl Johnson



More information about the Python-ideas mailing list